Tkinter标签丢失 – Python工作不正常?

huangapple go评论60阅读模式
英文:

Tkinter Label is missing - Python not working correctly?

问题

I'm trying to get started with Tkinter.

I wrote my first little piece of code. A window opens and a button appears, but the label is missing.

import tkinter as tk

def button_click():
    label.config(text="Button was clicked!")

root = tk.Tk()
root.title('Test')
root.geometry('400x300')
root.pack_propagate(False)

label = tk.Label(root, text="Hello World!")
label.pack()

button = tk.Button(root, text="Click me!", command=button_click)
button.pack()

root.mainloop()
type here

The window is black with a white button.
When I just use the label without a button, the window turns white and is completely empty.

Just tried the code on a different device, and there it works.
I'm not sure, but I think something with my Python settings is wrong; maybe I installed it wrongly. I'm working in PyCharm.

英文:

I'm trying to get started with Tkinter.

I wrote my first little piece of code. A window opens and a button appears, but the label is missing.

import tkinter as tk

def button_click():
    label.config(text="Button was clicked!")

root = tk.Tk()
root.title('Test')
root.geometry('400x300')
root.pack_propagate(False)

label = tk.Label(root, text="Hello World!")
label.pack()

button = tk.Button(root, text="Click me!", command=button_click)
button.pack()

root.mainloop()
type here

The window is black with a white button.
When i just use the label without a button the window turns white and is completly empty.

Just tried the code on different device and there it works.
Im not sure, but I think something with my python settings is wrong, maybe I installed it wrongly. Im working in PyCharm

答案1

得分: 1

来编辑Op 使用 MacOS

如果你正在使用 MacOS请移除前缀 `tk.`

```python
from tkmacosx import Label, Button
import tkinter as tk

def button_click():
    label.config(text="按钮被点击了!")

root = tk.Tk()
root.title('测试')
root.geometry('400x300')
root.pack_propagate(False)

label = Label(root, text="你好,世界!")
label.pack()

button = Button(root, text="点击我!", command=button_click)
button.pack()

root.mainloop()
英文:

Edit: Op using MacOS.

If you are using MacOS. Then remove prefix tk.

from tkmacosx import Label, Button
import tkinter as tk

def button_click():
    label.config(text="Button was clicked!")

root = tk.Tk()
root.title('Test')
root.geometry('400x300')
root.pack_propagate(False)

label = Label(root, text="Hello World!")
label.pack()

button = Button(root, text="Click me!", command=button_click)
button.pack()

root.mainloop()

huangapple
  • 本文由 发表于 2023年5月22日 17:56:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76304985.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定