我根据网上资料制作了一个可以随机生成编号的小工具,界面如下。

初步完成后想要重构一下,以便后续增加内容。但在重构过程中遇到一个问题,就是在生成编号的函数中需要调用tkinter的delete和insert方法,如
entry_vin.delete(0, "end")
entry_vin.insert("end", vin)
text_vin.insert(tk.END, vin + '\n')
而在定义按钮时,又需要调用生成编号的函数名creat_vin
btn1 = tk.Button(root,text='生成VIN码',command=creat_vin)
这样相互调用就不知道该怎么写了,陷入了死循环,希望有大手子可以帮忙指导下重构或者写代码的思路,感激不尽!代码在下面。
import string
import tkinter as tk
import random
vins=[]
plates=[]
batteries=[]
def creat_vin():
vin_start = 'LFWADRJF0110'
numbers = [str(random.randint(0,9)) for _ in range(5)]
vin_end = ''.join(numbers)
vin = vin_start + vin_end
if vin not in vins:
vins.append(vin)
entry_vin.delete(0, "end")
entry_vin.insert("end", vin)
text_vin.insert(tk.END, vin + '\n')
return vin
def creat_plate():
plate_start = '浙'
chars=['A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z']
plate_mid = random.choice(chars)
plate_end = random.choices(str(string.digits)+''.join(chars),k=5)
plate = plate_start + plate_mid + ''.join(plate_end)
if plate not in plates:
plates.append(plate)
entry_plate.delete(0, "end")
entry_plate.insert("end", plate)
text_plate.insert(tk.END, plate + '\n')
return plate
def creat_battery():
batteryNo = str(random.randint(10**11,10**13-1))
if batteryNo not in batteries:
batteries.append(batteryNo)
entry_battery.delete(0, "end")
entry_battery.insert("end", batteryNo)
text_battery.insert(tk.END, batteryNo + '\n')
return batteryNo
root = tk.Tk()
root.title('随机生成工具')
root.geometry('510x370+150+200')
btn1 = tk.Button(root,text='生成VIN码',command=creat_vin)
label_vin = tk.Label(root,text='新VIN码')
entry_vin = tk.Entry(root,width=18)
label_vin_old = tk.Label(root,text='已存在VIN码')
text_vin = tk.Text(root,width=18,height=15)
btn1.place(x=75,y=10)
label_vin.place(x=50,y=55)
entry_vin.place(x=50,y=75)
label_vin_old.place(x=50,y=95)
text_vin.place(x=50,y=115)
btn2 = tk.Button(root,text='生成车牌号',command=creat_plate)
label_plate = tk.Label(root,text='新牌号')
entry_plate = tk.Entry(root,width=10)
label_plate_old = tk.Label(root,text='已存在车牌号')
text_plate = tk.Text(root,width=12,height=15)
btn2.place(x=200,y=10)
label_plate.place(x=200,y=55)
entry_plate.place(x=200,y=75)
label_plate_old.place(x=200,y=95)
text_plate.place(x=200,y=115)
btn3 = tk.Button(root,text='生成电池编号',command=creat_battery)
label_battery = tk.Label(root,text='新电池编号')
entry_battery = tk.Entry(root,width=15)
label_battery_old = tk.Label(root,text='已存在电池编号')
text_battery = tk.Text(root,width=15,height=15)
btn3.place(x=320,y=10)
label_battery.place(x=320,y=55)
entry_battery.place(x=320,y=75)
label_battery_old.place(x=320,y=95)
text_battery.place(x=320,y=115)
root.mainloop()