我正在嘗試在文本輸入框中生成一個亂數。它不起作用,因為我不確定如何共享變數。如果有幫助,我將在 Visual Studio 代碼中使用 python tkinter。變數receipt_no 應該在文本輸入框中生成1000-9999 之間的亂數。我收到一個錯誤,即“str”物件沒有屬性“set”。
import tkinter as tk
import random
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.shared_data = {"receipt_no":tk.IntVar,
"receipt.no":tk.IntVar,
"receipt.no".set(str(random.randint(1000,9999))):tk.IntVar}
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage,RandomPage):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("StartPage")
def show_frame(self, page_name):
frame = self.frames[page_name]
'''Show a frame for the given page name'''
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent, bg='#3d3d5c')
self.controller = controller
def next():
controller.show_frame('RandomPage')
next_button = tk.Button(text='Next',
command=next,
relief='raised',
borderwidth=3,
width=18,
height=2)
next_button.place(x=1090, y=475)
class RandomPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent, bg='#3d3d5c')
self.controller = controller
order_number = tk.Label(self,
text="Customer order number",
font=('arial', 20, 'bold'),
foreground='#ffffff',
background='#33334d')
order_number.place(anchor=tk.N, bordermode=tk.INSIDE, x=200, y=500)
order_number_entry =tk.Entry(self,
width=12,
font=('Arial 20'),
textvariable=self.controller.shared_data["receipt_no"])
order_number_entry.place(anchor=tk.N, bordermode=tk.INSIDE, x=500, y=500)
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
我試圖設定該值并嘗試將其分享給不同的班級。我期望得到一個介于 1000-9999 之間的隨機生成的數字。
uj5u.com熱心網友回復:
由于您正在創建一個字典來獲取receipt_no設定 Entry 小部件文本的值,因此不要使用 .set 生成其值,只需創建一個tk.IntVar()變數和一個string變數來存盤亂數。
self.shared_data = {"receipt_no":tk.IntVar(),
"random_receipt_no":str(random.randint(1000,9999))}
現在,要設定 Entry 小部件的文本,您可能需要使用insert方法:
order_number_entry =tk.Entry(self,
width=12,
font=('Arial 20'),
textvariable = self.controller.shared_data["receipt_no"])
order_number_entry.insert(0,self.controller.shared_data["random_receipt_no"])
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/453975.html
上一篇:TypeError:Entry.get()得到了一個意外的關鍵字引數“textvariable”
下一篇:如何在螢屏上傳播小部件?
