【问题标题】:Connect a message box to a button将消息框连接到按钮
【发布时间】:2013-08-10 03:54:54
【问题描述】:

我希望能够单击按钮并让消息框显示生成的代码。以下是部分代码:

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) 

【问题讨论】:

  • 这是 Tkinter,对吧?值得一提/标记您正在使用的 GUI 框架。

标签: python button user-interface tkinter messagebox


【解决方案1】:

用 cmets 修复了一些问题:

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) 

【讨论】:

  • 在函数中定义函数绝不是好的形式。改为查看 lambda 函数。
  • @The-IT 我不同意。如果您尝试生成一个短函数,Lambda 函数很方便,但是在函数中定义一个函数是完全可以接受的,如果生成的函数超过一两行,甚至更可取。
  • 你在函数中的函数对我来说甚至没有意义。它接受参数sVariable,然后从不使用它。你最好删除代码的整个部分和callback = makeCallback(sVar),然后在按钮中执行command=lambda s=s: sVar.set(s)
  • 实际上,您在几件事上是对的-我犯了一个错误-我的意思是写 sVariable.set(s),实际上这里不需要回调工厂,因为 sVar 定义在模块级别 - 我习惯于在类中编写 GUI,您需要一个回调工厂(或 lambda 语句)。但是有很多情况下回调工厂很有用。例如,如果回调需要执行多个命令,你会怎么做? lambda 函数开始变得难以阅读。
  • 我要做的是,如果需要,我将拥有一个普通函数,它可以调用一堆其他函数。这可以很容易地在课堂上完成。另外,我总是被告知在函数中定义函数总是不好的形式,我同意,因为我没有看到有必要这样做的情况。
猜你喜欢
  • 1970-01-01
  • 2012-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多