【问题标题】:Can't import tkinter, tkinter is not defined - it seems not to be the usual problem无法导入 tkinter,未定义 tkinter - 这似乎不是常见问题
【发布时间】:2019-01-06 17:00:09
【问题描述】:

无论我使用什么方法导入 tkinter,Python3 都会给我这个或其他错误。

我在网上搜索了我的问题的解决方案,但没有一个有效。我正在运行最新版本的 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()

结果是:

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.

我无法弄清楚程序为什么不起作用。它应该显示一个按钮,如果你按下它,它应该显示“WEWE”。对不起我可能糟糕的英语。

【问题讨论】:

  • 您从命名空间 tkinter 导入了所有名称,而不是命名空间本身。删除 tkinter。 maniloop() 应该是 main_window.mainloop。

标签: python-3.x tkinter


【解决方案1】:

问题在于你使用from tkinter import *,然后将按钮功能用作tkinter.Button。当您使用from xxx import * 时,您不再使用“xxx”包名(所以只需Button())。否则只需使用import tkinter,然后使用tkinter.Button()

我个人更喜欢import xxx 用于较大的脚本,因为它更清楚方法来自哪里。

除此之外,您的代码中的“click_function”还有另一个问题。你应该让它成为一个实际的功能。并且 tkinter.Button() 是大写的 '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()

【讨论】:

    【解决方案2】:

    试试这个方法:

    #!/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()
    

    【讨论】:

    • 我的示例向您展示了您在导入 tkinter 时做错了什么,但这并不意味着您的代码会因为您的 click_function 定义而工作!
    • 谢谢,现在程序开始了。但是...为什么如果我单击按钮它不会打印“WEWE”,而是在程序开始时打印它?
    • @xevius48_dev:那是因为您刚刚将 click_function 定义为在执行 main() 时运行的变量。使其成为一个实际的单独功能。请参阅我的答案中的编辑。
    猜你喜欢
    • 2013-05-13
    • 2017-01-28
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    相关资源
    最近更新 更多