I am going to be writing a program with this starter file provided to me by my instructor. The issue is is that the file she gave us does not run. I don't know if this is because I am using IDLE, or if the code only runs on certain operating systems.
For example, I use Windows, but my teacher uses both Windows and Linux systems. I cannot get a hold of her to figure out the issue, so I was hoping you guys could.
Currently, when I run the starter file, I get an error:
TypeError: main() is not defined.
When I switch main()
for GUI()
at the bottom of the program, I get a new error:
TypeError: __init__() missing 1 required positional argument: 'rootWindow'
This is the full code:
from tkinter import*
from tkinter import tk
class GUI:
def __init__(self,rootWindow):
self.label = ttk.Label(rootWindow, text="Hellow World!")
self.label.grid(row=0,column=0)
self.button1=ttk.Button(rootWindow,text="Hello",command=self.hello)
self.button1.grid(row=0,column=1)
self.button2=ttk.Button(rootWindow,text="Bye",command=self.bye)
self.button2.grid(row=0,column=2)
def bye(self):
self.label.config(text="GoodbyeWorld!")
def hello(self):
self.label.config(text="HelloWorld!")
def main():
global label
rootWindow = Tk()
gui = GUI(rootWindow)
rootWindow.mainloop()
main()
There are two problems with this code:
You need to unindent the main
function, because otherwise you can't just call main
because it is a part of the GUI
class.
The imports are messed up. You need to import tkinter as ttk
because otherwise ttk
is undefined, and import Tk
instead of import tk
.
Note that I am using Python 3, so yours may be slightly different if you're using Python 2.
The full corrected code is below:
import tkinter as ttk
from tkinter import Tk
class GUI:
def __init__(self,rootWindow):
self.label = ttk.Label(rootWindow, text="Hellow World!")
self.label.grid(row=0,column=0)
self.button1=ttk.Button(rootWindow,text="Hello",command=self.hello)
self.button1.grid(row=0,column=1)
self.button2=ttk.Button(rootWindow,text="Bye",command=self.bye)
self.button2.grid(row=0,column=2)
def bye(self):
self.label.config(text="GoodbyeWorld!")
def hello(self):
self.label.config(text="HelloWorld!")
def main():
global label
rootWindow = Tk()
gui = GUI(rootWindow)
rootWindow.mainloop()
main()