代码

时间:2017-12-20 15:58:03

标签: python tkinter

今天我在编写代码时遇到了这个错误,当我启动代码时,定义应该在我点击按钮时起作用,但是一旦窗口出现就启动了。 目标: 当我点击按钮时,定义应该启动 这是我的代码:

from tkinter import *
from tkinter import messagebox
import uuid
from urllib.request import urlopen
import io
import base64
def generate_pair(string_length=5):
    """Generate 1 pair of serial"""
    random = str(uuid.uuid4())
    random = random.upper()
    random = random.replace("-","")
    return random[0:string_length]
def generate(length):
    l1 = generate_pair(length)
    l2 = generate_pair(length)
    l3 = generate_pair(length)
    l4 = generate_pair(length)
    l5 = generate_pair(length)
    final = l1+"-"+l2+"-"+l3+"-"+l4+"-"+l5+"-"
    messagebox.showinfo("Generated serial key", "Generated serial key :"+final)
image_url = "https://s14.postimg.org/eva19579t/button.png"
image_byt = urlopen(image_url).read()
image_b64 = base64.encodestring(image_byt)
root = Tk()
root.configure(background="white")
root.minsize(350, 350)
root.maxsize(350, 350)
#Menu bar
menubar = Menu(root)
menubar.add_command(label="About")
menubar.add_command(label="Contact!")
root.config(menu=menubar)
#End Menubar
root.title("Serial Key Generator")
f = Frame(root, bg='white')
f.place(anchor="center", relx=.5, rely=.5)
f.pack()
l2 = Label(f, text="\n\n\n\n\n\n", background="white").pack()
Label(f, text="Length of Serial Key", background='white').pack()
v = IntVar()
radiogroup = Frame(f)
radiogroup.pack()
R1 = Radiobutton(radiogroup, text="1", variable=v, value=1)
R1.config(background='white')
R1.pack(side="left")
R2 = Radiobutton(radiogroup, text="2", variable=v, value=2)
R2.config(background="white")
R2.pack(side="left")
R3 = Radiobutton(radiogroup, text="3", variable=v, value=3)
R3.config(background="white")
R3.pack(side="left")
R4 = Radiobutton(radiogroup, text="4", variable=v, value=4)
R4.config(background="white")
R4.pack(side="left")
R5 = Radiobutton(radiogroup, text="5", variable=v, value=5)
R5.config(background="white")
R5.pack(side="left")
radiovalue = v.get()
generate_b = Button(f)
img = PhotoImage(data=image_b64)
generate_b.config(image=img)
generate_b.bind("<Button-1>", generate(radiovalue))
generate_b.pack()
root.mainloop()

1 个答案:

答案 0 :(得分:3)

替换:

generate_b.bind("<Button-1>", generate(radiovalue))

使用:

generate_b.config(command=lambda arg=radiovalue: generate(radiovalue))

两个选项(bind(SEQUENCE, func)functkinter.widget.config(command) command都需要引用到函数名称而不是实际的函数调用。

因此,当计算机到达其行时,您的功能会立即运行。为了防止替换:

generate_b.bind("<Button-1>", generate(radiovalue))

使用:

generate_b.bind("<Button-1>", lambda arg=radiovalue: generate(radiovalue))

此外,您可能更愿意使用按钮自己的command选项来捕捉所有按钮按下,包括键盘按钮,然后进一步替换为:

generate_b.config(command= lambda arg=radiovalue : generate(radiovalue))

或:

generate_b['command'] = lambda arg=radiovalue : generate(radiovalue)