简体   繁体   English

导入Tkinter并制作窗口时出现错误

[英]Getting error when importing Tkinter and making a window

Here is my code guys: 这是我的代码专家:

from tkinter import *

root = Tk()
theLabel = Label(root, 'Hello World')
theLabel.pack()
root.mainloop()

Here is the error: 这是错误:

Traceback (most recent call last): File "C:/Users/argel/PycharmProjects/day2/rockpaper.py", line 4, in theLabel = Label(root, 'Hello World') File "C:\\Users\\argel\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\tkinter__init__.py", line 2760, in init Widget. 追溯(最近一次通话最近):文件“ C:/Users/argel/PycharmProjects/day2/rockpaper.py”,第4行,在LabLab = Label(根目录,“ Hello World”)中,文件“ C:\\ Users \\ argel \\ AppData \\ Local \\ Programs \\ Python \\ Python36-32 \\ lib \\ tkinter__init __。py“,第2760行,在初始小部件中。 init (self, master, 'label', cnf, kw) File "C:\\Users\\argel\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\tkinter__init__.py", line 2289, in init classes = [(k, v) for k, v in cnf.items() if isinstance(k, type)] AttributeError: 'str' object has no attribute 'items' 初始化 (自己,主文件,“标签”,cnf,kw)文件“ C:\\ Users \\ argel \\ AppData \\ Local \\ Programs \\ Python \\ Python36-32 \\ lib \\ tkinter__init __。py”,第2289行, init类= [ (如果为isinstance(k,类型),则为cnf.items()中的k,v的(k,v)] AttributeError:'str'对象没有属性'items'

Thank you for your help 谢谢您的帮助

Just change theLabel = Label(root, 'Hello World') to theLabel = Label(root, text='Hello World') and it will work. 只需将theLabel = Label(root, 'Hello World')更改为theLabel = Label(root, text='Hello World')

I have a suggestion to improve your code: 我建议改善您的代码:

Rather than from tkinter import * use import tkinter as tk . 而不是from tkinter import *使用import tkinter as tk

from tkinter import * is actually discouraged so I strongly recommend you do not use this method. from tkinter import *不鼓励,所以我强烈建议您不要使用此方法。

Remember you would also need to change your script slightly if you do. 请记住,如果这样做,您还需要稍微更改脚本。 It would look like this: 它看起来像这样:

import tkinter as tk

root = tk.Tk()
theLabel = tk.Label(root, text='Hello World')
theLabel.pack()
root.mainloop()

For more information the differences between imports please see this post. 有关更多信息,请参见这篇文章。

I hope it solved your problem. 希望它能解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM