简体   繁体   English

Tkinter Label 不像我想象的那样工作

[英]Tkinter Label doesn't work as I thought it does

Beginner programmer here currently trying to learn Tkinter for a school assignment.这里的初学者程序员目前正在尝试学习 Tkinter 以完成学校作业。 I have a GUI class that stores the Tkinter labels etc, the labels are innitiated like this:我有一个 GUI class 存储 Tkinter 标签等,标签是这样发起的:

# GUI for Player 1
self.player_1_name_field = Label(
    self.root,
    text="Player 1",
    font=GUI_Settings.player_information_font,
    anchor=W,
    background=GUI_Settings.playerfield_active_color
)

I then create a Game() object that looks like this:然后我创建一个 Game() object,如下所示:

class Game():
def __init__(self):
    self.GUI = GUI()
    self.GUI.initializeBoard()
    self.GUI.root.mainloop()

When I run the code, the labels do get created and are where they are supposed to be, but are completely black.当我运行代码时,标签确实被创建并且是它们应该在的位置,但完全是黑色的。 Once I move or resize the window it instantly becomes how I want it to be, it just behaves weird when at the start of the code一旦我移动或调整 window 的大小,它就会立即变成我想要的样子,只是在代码开始时表现得很奇怪

The interesting thing is that I also have a Canvas and a List that work perfectly fine, only the Labels are not cooperative有趣的是,我还有一个 Canvas 和一个工作正常的列表,只有标签不合作

If you need further info, just ask for it!如果您需要更多信息,请索取! Thank you!谢谢!

Edit 1: I have a function called drawWindow() that redraws the chessboard when I re-configure the window.编辑 1:我有一个名为 drawWindow() 的 function,当我重新配置 window 时,它会重绘棋盘。 In the init of the GUI class I set self.root.bind("<Configure>", self.drawWindow) .在 GUI class 的初始化中,我设置self.root.bind("<Configure>", self.drawWindow) If I remove that line of code, the Labels work but the Canvas doesn't anymore.如果我删除那行代码,标签会起作用,但 Canvas 不再起作用。 I'm so confused.我很混乱。 For anyone wanting to take a look at my tiny code: https://codeshare.io/DZYzyZ对于任何想看看我的小代码的人: https://codeshare.io/DZYzyZ

This is a tricky issue.这是一个棘手的问题。 Your problem come from the bind of the configure event.您的问题来自配置事件的绑定。 Bind to the root window, it is applied to all sub-widgets of the window, which cause the bug (configure on label seems to be a bad thing:D ).绑定到根window,应用于window的所有子widget,这会导致bug(在label上配置似乎是一件坏事:D)。

This will solve your issue (line 202):这将解决您的问题(第 202 行):

self.chessboard.bind("<Configure>", self.drawWindow)

instead of:代替:

self.root.bind("<Configure>", self.drawWindow)

Result without moving or resizing the window:结果无需移动或调整 window 的大小: 在此处输入图像描述

I found the information here (french forum).我在这里找到了信息(法语论坛)。

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

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