1 回答

TA貢獻1829條經驗 獲得超7個贊
這是我制作的一個課程,以便它支持此類活動。
from tkinter import *
class Custom(Entry): #inheriting from the Entry class
def ret(self):
if self.get() == '': # if empty then assign
return 'Unknown'
else:
return self.get() # else give the same thing out
root = Tk()
root.title("Form")
name = Label(root, text="Name", width=20,bg = "black", fg="red")
name.place(x=150, y=50)
a = Custom(root, width=20, bg = "black", fg="red") #instantiating using all the same option you did before
a.place(x=150, y=100)
print(a.ret()) #Prints unknown
print(a.ret() == a.get()) #prints false obviously, just a testimony ;)
root.mainloop()
這里必須要用到a.ret(),為什么呢?因為這就是我在課堂上定義它的方式。您可以使用a.get(),但它只會給您通常的空白字符串。get()而且我認為除了編輯__init__.pytkinter 文件之外不可能覆蓋現有方法,如果我錯了,請告訴我。
您還可以將類縮短為多行,例如:
class Custom(Entry):
def ret(self):
return 'Unknown' if self.get() == '' else self.get() #does the same thing as before
請記住,您可以替換'Unknown'為您喜歡的任何內容。
這不是最好的代碼,因為我以前沒有使用過類。為什么使用類?因為我相信默認的 tkinter 不可能做到這一點。那么為什么不直接創建一個自定義類并獲得這種效果;)
您應該如何在您的項目中使用它?只需將所有替換Entry(..)為Custom(..). 它也支持普通小部件所做的所有選項Entry。
在此處進行更改以修復錯誤:
def click():
kilograms = a.ret()
kilo_float = a.ret()
try:
kilo_float = float(kilograms)
except ValueError:
pass
print(kilo_float)
希望這對您有幫助。如果您有任何疑問或錯誤,請告訴我。
添加回答
舉報