我是python的新手。
我试图用tkinter编写代码。 单击一个按钮,它应该打开另一个窗口并关闭上一个窗口。 该代码正确关闭了上一个窗口。
但是问题在于它还在屏幕的侧面打开了另一个空窗口。
这是我的代码:
# The first part got no problem
from tkinter import *
import time
class Start:
def __init__(self):
self.first_screen = Tk()
self.win_width = 500
self.win_height = 500
self.screen_width = self.first_screen.winfo_screenwidth()
self.screen_height = self.first_screen.winfo_screenheight()
self.x_position = (self.screen_width / 2) - (self.win_width / 2)
self.y_position = (self.screen_height / 2) - (self.win_height / 2)
self.first_screen.title("Number game")
self.first_screen.config(bg="#ffff00")
self.first_screen.geometry("%dx%d+%d+%d" % (self.win_width, self.win_height, self.x_position, self.y_position))
self.btn_play = Button(self.first_screen, text="Start", command=self.btn_play_click_action, width="10")
self.btn_play.pack(side="top")
self.btn_play.place(height=40, width=200, x=150, y=200)
self.first_screen.mainloop()
# This is where the problem happened
def btn_play_click_action(self):
time.sleep(1)
self.first_screen.destroy()
self.second_screen = Toplevel()
self.second_screen.geometry("%dx%d+%d+%d" % (self.win_width, self.win_height, self.x_position, self.y_position))
self.second_screen.title("Number game")
self.second_screen.config(bg="#eeee00")
self.label1 = Label(self.second_screen, width=50, bg="#000000")
self.label1.pack(side="top")
self.second_screen.mainloop()
Start()
编辑:
当我删除“ self.first_screen.destroy()”这一行时,就没有问题了。
也许是因为Toplevel需要父窗口。但是我需要关闭上一个窗口。在这种情况下,我该怎么办?
答案 0 :(得分:0)
您无法破坏程序的根窗口self.first_screen = Tk()。 此外,您不需要顶级窗口的主循环。 您可以使用.withdraw()方法而不是.destroy()来隐藏根窗口
这是您更新的代码-
from tkinter import *
import time
class Start:
def __init__(self):
self.first_screen = Tk()
self.win_width = 500
self.win_height = 500
self.screen_width = self.first_screen.winfo_screenwidth()
self.screen_height = self.first_screen.winfo_screenheight()
self.x_position = (self.screen_width / 2) - (self.win_width / 2)
self.y_position = (self.screen_height / 2) - (self.win_height / 2)
self.first_screen.title("Number game")
self.first_screen.config(bg="#ffff00")
self.first_screen.geometry("%dx%d+%d+%d" % (self.win_width, self.win_height, self.x_position, self.y_position))
self.btn_play = Button(self.first_screen, text="Start", command=self.btn_play_click_action, width="10")
self.btn_play.pack(side="top")
self.btn_play.place(height=40, width=200, x=150, y=200)
self.first_screen.mainloop()
# This is where the problem happened
def btn_play_click_action(self):
time.sleep(1)
self.first_screen.withdraw()
self.second_screen = Toplevel()
self.second_screen.geometry("%dx%d+%d+%d" % (self.win_width, self.win_height, self.x_position, self.y_position))
self.second_screen.title("Number game")
self.second_screen.config(bg="#eeee00")
self.label1 = Label(self.second_screen, width=50, bg="#000000")
self.label1.pack(side="top")
答案 1 :(得分:-1)
没有必要在Toplevel()
中创建另一个窗口。您可以简化操作→输入self.second_screen = Toplevel()
代替self.second_screen = Tk()
。