Reputation: 21
Python3 gives me this or other errors, whatever method i use to import tkinter.
I searched online a solution to my problem but none worked. I am running the latest version of Ubuntu.
#!/usr/bin/env python3
from tkinter import *
def main():
main_window = tkinter.Tk()
main_window.title("free communism here")
click_function = print("WEWE")
communism_button = tkinter.button(text = "click for free communism", command = click_function, height = 40, width = 120)
communism_button.pack()
tkinter.mainloop()
main()
The result is:
Traceback (most recent call last):
File "communism button.py", line 10, in <module>
main()
File "communism button.py", line 4, in main
main_window = tkinter.Tk()
NameError: name 'tkinter' is not defined.
I can't figure out why the program doesn't work. It should display a button and if you press it, it should display "WEWE". Sorry for my probably bad english.
Upvotes: 1
Views: 54
Reputation: 2696
The problem lies in the fact that you use from tkinter import *
and then use the button function as tkinter.Button
. When you use from xxx import *
you don't use the 'xxx' package name anymore (so just Button()
). Otherwise just use import tkinter
, after which you do use tkinter.Button()
.
I personally prefer import xxx
for larger scripts, because it's more clear where a method comes from.
Besides that, your code still has another problem with your 'click_function'. You should make that an actual function. And tkinter.Button() is with a capital 'B'
import tkinter
def click_function():
print("WEWE")
def main():
main_window = tkinter.Tk()
main_window.title("free communism here")
communism_button = tkinter.Button(text = "click for free communism", command = click_function, height = 40, width = 120)
communism_button.pack()
main_window.mainloop() # call here main_window instead of tkinter
main()
Upvotes: 1
Reputation:
Try this way:
#!/usr/bin/env python3
from tkinter import *
def main():
main_window = Tk()
main_window.title("free communism here")
click_function = print("WEWE")
communism_button = Button(text = "click for free communism", command = click_function, height = 40, width = 120)
communism_button.pack()
main_window.mainloop()
main()
Upvotes: 0