Python Tkinter开发:标签(Label)无法显示问题求助
Hey there, let's dig into why your Tkinter Label isn't displaying. Looking at your code snippet, there are a couple of critical issues that are almost certainly causing this problem:
1. Incorrect Indentation for init_window
Right now, your init_window function is defined outside the Window class instead of being a method inside it. When your __init__ method tries to call self.init_window(), this will throw an error (you might not be seeing it if you're not catching exceptions), which stops the rest of your UI setup from running.
Fix this by indenting the init_window definition so it's aligned with the __init__ method inside the Window class.
2. Missing Layout Manager for Your Label
Assuming your showtxt method is supposed to create and display the Label, a super common mistake is forgetting to call a layout method like pack(), grid(), or place() on the Label component. Tkinter won't render any widget unless you tell it how to position it in the window.
Corrected Full Code Example
Here's your code with the fixes applied, plus a working showtxt method that properly displays a Label:
from tkinter import * class Window(Frame): def __init__(self, master = None): Frame.__init__(self, master) self.master = master self.init_window() # Now properly indented as a class method def init_window(self): self.master.title("Ethics and similar topics quiz") self.pack(fill=BOTH, expand=1) StartButton = Button(self, text="Start Quiz", fg = "Purple", command=self.showtxt) StartButton.config(height = 4 , width = 25) StartButton.pack(pady=20) # Don't forget to layout the button too! def showtxt(self): # Create the Label and use pack() to display it quiz_label = Label(self, text="Welcome to the Ethics Quiz!", font=("Arial", 14)) quiz_label.pack(pady=10) # Initialize the Tk root and your window root = Tk() root.geometry("400x300") # Set a window size for better visibility app = Window(root) root.mainloop()
Key Fixes Recap
- Indented
init_windowto be part of theWindowclass - Added
pack()to the StartButton (you might have missed this too!) - Implemented
showtxtwith a Label that usespack()to ensure it renders
Give this a try, and your Label should show up when you click the "Start Quiz" button!
内容的提问来源于stack exchange,提问作者Iles-2003

