我正在嘗試從串列中選擇隨機名稱以顯示在 tkinter GUI 的文本框中,并帶有一個按鈕,并且每次單擊按鈕時都需要在 tkinter 腳本中顯示新的繪圖。
到目前為止,這是我的代碼:
from tkinter import *
from random import sample
root = Tk()
root.title('Name Picker')
root.iconbitmap('c:/myguipython/table.ico')
root.geometry("400x400")
def pick():
# 5 entries
entries = ["1st name","2nd name","3rd name","4th name","5th name"]
# convert to a set
entries_set = set(entries)
# convert back to a list
unique_entries = list(entries_set)
number_of_items = 2
rando = sample(unique_entries, number_of_items)
rando1 = sample(unique_entries, number_of_items)
my_text = Text(root, width=40, height=10, font=("Helvetica", 18))
my_text.pack(pady=10)
if len(my_text.get(1.0, END)) != 0:
my_text.delete(1.0, END)
my_text.insert(INSERT, rando rando1)
my_text.pack(expand= 1, fill= BOTH)
topLabel = Label(root, text="Picked Names", font=("Helvetica", 24))
topLabel.pack(pady=20)
winButton = Button(root,
text="pick names",
font=("Helvetica", 24), command=pick)
winButton.pack(pady=20)
root.mainloop()
我需要幾個隨機抽取的子集(我使用 rando 和 rando1 值作為上面的示例)。
當我第一次單擊該按鈕時,它確實按預期顯示了名稱字串,但是當我再次單擊時,沒有任何變化(名稱保持不變)。
我需要的是每次單擊按鈕時都顯示新的繪圖。如果不為空,我想清除文本框并在再次單擊空文本框時重新填充(使用上面的洗掉和插入陳述句)。但這行不通。
經過一番研究,我發現了這個片段:
# Import package and it's modules
from tkinter import *
# text_update function
def text_updation(language):
text.delete(0, END)
text.insert(0, language)
# create root window
root = Tk()
# root window title and dimension
root.title("GeekForGeeks")
# Set geometry (widthxheight)
root.geometry('400x400')
# Entry Box
text = Entry(root, width=30, bg='White')
text.pack(pady=10)
# create buttons
button_dict = {}
words = ["Python", "Java", "R", "JavaScript"]
for lang in words:
# pass each button's text to a function
def action(x = lang):
return text_updation(x)
# create the buttons
button_dict[lang] = Button(root, text = lang,
command = action)
button_dict[lang].pack(pady=10)
# Execute Tkinter
root.mainloop()
它似乎與我需要的很接近,但字典的使用似乎與我轉換為集合然后回傳到串列然后在代碼的文本框中顯示之前的采樣不兼容。
我如何使用給定的代碼片段來解決這個問題?或者,如果無法使用此代碼段,您會建議尋找其他什么其他的洞察力解決方案?感謝您的幫助。
uj5u.com熱心網友回復:
在您的代碼中,您每次按下按鈕時都會呼叫 Text 小部件的小部件建構式。您應該做的是在函式之外創建小部件并使用該函式來更新小部件的內容。還有相當多的錯誤代碼。
例如:
from tkinter import *
from random import sample
root = Tk()
root.title('Name Picker')
root.iconbitmap('c:/myguipython/table.ico')
root.geometry("400x400")
def pick():
entries = ["1st name","2nd name","3rd name","4th name","5th name"]
number_of_items = 2
rando = sample(entries, number_of_items)
rando1 = sample(entries, number_of_items)
my_text.delete(1.0, END)
my_text.insert(INSERT, rando rando1)
topLabel = Label(root, text="Picked Names", font=("Helvetica", 24))
topLabel.pack(pady=20)
winButton = Button(root, text="pick names", font=("Helvetica", 24), command=pick)
winButton.pack(pady=20)
my_text = Text(root, width=40, height=10, font=("Helvetica", 18))
my_text.pack(pady=10)
root.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/525491.html
上一篇:如果版本高于16位最大值,Cocoa框架“當前庫版本”會發出32位截斷警告
下一篇:ViewPager2不切換片段
