![](/img/trans.png)
[英]How can I combine tkinter and wxpython without freezing window - python?
[英]How can I combine this tkinter label and string into one window?
在我正在研究的一個程序中,有一個 tkinter 標簽/按鈕可以啟動紙牌游戲(我正在使用的程序)和另一個 window 有一個字符串,上面寫着“歡迎來到紙牌游戲”。 這是代碼的 tkinter 部分:
import tkinter
window = tkinter.Tk()
print()
from tkinter import *
def quit():
global root
root.quit()
root = Tk()
while True:
label = tkinter.Label(window, text = "Welcome to the card game! (During name registration only use characters)").pack()
Button(root, text="Start Game", command=quit).pack()
root.mainloop()
然而,當我運行程序時,它們各自出現在自己的 window 屏幕中,而用戶在一個 window 中擁有選項會更方便。
無論如何要合並它們嗎?
編輯 - (使用 root 使用按鈕和文本已解決問題。)
這里有很多不應該出現在這么小的代碼集中的事情。
讓我們分解一下。
首先是你的進口。 您從 tkinter 多次導入。 您只需要導入一次,就可以使用帶有適當前綴的所有內容。 首選方法是import tkinter as tk
這樣您就不會覆蓋任何其他導入或內置方法。
接下來,我們需要刪除您的Tk()
實例之一,因為 tkinter 應該只有一個。 對於其他 windows 使用Toplevel()
。
在您的退出 function 中,您不需要定義全局,因為您沒有在此處分配值,因此 function 將在全局命名空間中查找 root。
接下來讓我們刪除空的打印語句。
接下來確保您的 label 和按鈕都分配了相同的容器。 這就是您在不同的 windows 中看到它們的原因。
接下來重命名您的 function ,因為quit
是內置方法,不應被覆蓋。
最后,我們刪除了 while 語句,因為mainloop()
已經在循環 Tk 實例。 您無需自己管理。
這是您的代碼應如下所示(第二個 window 在這里沒有用處):
import tkinter as tk
def root_quit():
root.quit()
root = tk.Tk()
tk.Label(root, text="Welcome to the card game! (During name registration only use characters)").pack()
tk.Button(root, text="Start Game", command=root_quit).pack()
root.mainloop()
這是一個使用Toplevel
的示例,您可以了解它是如何使用的。
import tkinter as tk
def root_quit():
root.quit()
def game_window():
top = tk.Toplevel(root)
tk.Button(top, text='exit', command=root_quit).pack()
root = tk.Tk()
tk.Label(root, text="Welcome to the card game! (During name registration only use characters)").pack()
tk.Button(root, text="Start Game", command=game_window).pack()
root.mainloop()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.