我希望能够单击按钮并让消息框显示生成的代码。这是代码的一部分:
global s
letters = [random.choice('BCDFGHJKMPQRTVWXYYZ') for x in range(19)]
numbers = [random.choice('2346789') for x in range(6)]
s = letters + numbers
random.shuffle(s)
s = ''.join(s)
global Code
Code = Entry(state='readonly')
def callback():
Code = Entry(state='readonly', textvariable=s)
Code.grid(row=0, pady=20)
generate=PhotoImage(file='generate.gif')
G = Button(image=generate , command=callback, compound=CENTER)
G.grid(row=1, padx=206.5, pady=20)
答案 0 :(得分:0)
通过评论解决了一些问题:
from Tkinter import *
import random
root = Tk()
letters = [random.choice('BCDFGHJKMPQRTVWXYYZ') for x in range(19)]
numbers = [random.choice('2346789') for x in range(6)]
s = letters + numbers
random.shuffle(s)
s = ''.join(s)
# Rather than use global variables, which is generally a bad idea, we can make a callback creator function, which takes the formerly global variables as arguments, and simply uses them to create the callback function.
def makeCallback(sVariable):
def callback():
# This will set the text of the entry
sVar.set(s)
return callback
# Use a StringVar to alter the text in the Entry
sVar = StringVar(root)
# You can use an Entry for this, but it seems like a Label is more what you're looking for.
Code = Entry(root, state='readonly', textvariable=sVar)
# Create a callback function
callback = makeCallback(sVar)
Code.grid(row=0, pady=20)
generate=PhotoImage(file='generate.gif')
G = Button(root, image=None , command=callback, compound=CENTER)
G.grid(row=1, padx=206.5, pady=20)