我尝试制作一个数字生成器(所以如何通过乐透 - 数字从 - 到,并需要从中获取一些数量(例如:1-50中的6个数字))。 这是代码:`
from tkinter import *
def printer(event):
import random
s = random.sample(range("a", "b"),"c")
print(s)
return
root = Tk()
s = StringVar()
lab = Label(root, text="Minimum", font="Arial 10")
ent = Entry(root,width=20,bd=3,text="a")
lab.pack()
ent.pack()
lab = Label(root, text="Maximum", font="Arial 10")
ent = Entry(root,width=20,bd=3,text="b")
lab.pack()
ent.pack()
lab = Label(root, text="Quantity", font="Arial 10")
ent = Entry(root,width=20,bd=3,text="c")
lab.pack()
ent.pack()
but = Button(root, text="GO!",
width=20,height=5,
bg="green",fg="yellow")
but.bind("<Button-1>", printer)
but.pack()
lab = Label(root, text="Result", font="Arial 10")
ent = Entry(root,width=20,bd=3,text=(printer))
lab.pack()
ent.pack()
root.mainloop()`
但是,当我点击“开始”按钮时,我得到了:
"Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.4/tkinter/__init__.py", line 1490, in __call__
return self.func(*args)
File "/home/juri/lotto_gui.py", line 5, in printer
s = random.sample(range("a", "b"),"c")
TypeError: Can't convert 'int' object to str implicitly"
我做错了什么?请帮帮我!
答案 0 :(得分:2)
好的,我想我明白不了。我更改了您的代码以使其正常工作:
from tkinter import *
def printer(event):
global s # use global StringVar to show the results
import random
r_sample = random.sample(range(a.get(), b.get()), c.get())
# set the s variable with the random sample
s.set(",".join(map(str,r_sample)))
return
root = Tk()
s = StringVar()
# IntVars added here
a = IntVar()
b = IntVar()
c = IntVar()
lab = Label(root, text="Minimum", font="Arial 10")
ent = Entry(root,width=20,bd=3, textvariable=a)
lab.pack()
ent.pack()
lab = Label(root, text="Maximum", font="Arial 10")
ent = Entry(root,width=20,bd=3, textvariable=b)
lab.pack()
ent.pack()
lab = Label(root, text="Quantity", font="Arial 10")
ent = Entry(root,width=20,bd=3, textvariable=c)
lab.pack()
ent.pack()
but = Button(root, text="GO!",
width=20,height=5,
bg="green",fg="yellow")
but.bind("<Button-1>", printer)
but.pack()
lab = Label(root, text="Result", font="Arial 10")
ent = Entry(root,width=20,bd=3, textvariable=s)
lab.pack()
ent.pack()
root.mainloop()
基本上,我将a,b,c变量设为IntVar
。同时修复了printer
,以便它使用三个变量,并更新s
变量。