Tkinter 非常奇怪
Tkinter being extremely weird
所以我正在 Python 中开发一种编程语言。
这是我到目前为止的代码:
import tkinter as tk
import tkinter.messagebox as m
import sys
class IOscriptError(Exception):
pass
class Std:
def __init__(self):
self.root = tk.Tk()
self.root.title("STDOUT")
self.stdouttext = [""]
self.outstd = tk.Label(self.root, text=self.stdouttext)
self.outstd.pack()
def out(self, value):
self.stdouttext.append(value + "\n")
self.outstd.config(text=''.join(self.stdouttext))
def start(self):
self.root.mainloop()
std = Std()
class Gui:
def __init__(self):
pass
def newButton(self, val, command="m.showinfo('title', 'message')"):
self.b=tk.Button(std.root, text=val, command=command).pack()
gui = Gui()
std.out("Hello!")
std.out("How are you?")
gui.newButton("Hello!")
std.start()
问题是按钮 gui.b
的命令不是 运行。
我也尝试过使用 lambda.
就是行不通!
你能告诉我为什么会发生这种情况以及如何解决它吗?
谢谢!
问题是您试图将字符串而不是函数作为命令传递。而不是 command="m.showinfo('title', 'message')"
,尝试这样的事情:
def TestCommand():
m.showinfo('title', 'message')
class Gui:
def __init__(self):
pass
def newButton(self, val, command=TestCommand):
self.b=tk.Button(std.root, text=val, command=command).pack()
请记住,Button 构造函数采用 函数 作为命令参数,而不是字符串。
所以我正在 Python 中开发一种编程语言。
这是我到目前为止的代码:
import tkinter as tk
import tkinter.messagebox as m
import sys
class IOscriptError(Exception):
pass
class Std:
def __init__(self):
self.root = tk.Tk()
self.root.title("STDOUT")
self.stdouttext = [""]
self.outstd = tk.Label(self.root, text=self.stdouttext)
self.outstd.pack()
def out(self, value):
self.stdouttext.append(value + "\n")
self.outstd.config(text=''.join(self.stdouttext))
def start(self):
self.root.mainloop()
std = Std()
class Gui:
def __init__(self):
pass
def newButton(self, val, command="m.showinfo('title', 'message')"):
self.b=tk.Button(std.root, text=val, command=command).pack()
gui = Gui()
std.out("Hello!")
std.out("How are you?")
gui.newButton("Hello!")
std.start()
问题是按钮 gui.b
的命令不是 运行。
我也尝试过使用 lambda.
就是行不通!
你能告诉我为什么会发生这种情况以及如何解决它吗?
谢谢!
问题是您试图将字符串而不是函数作为命令传递。而不是 command="m.showinfo('title', 'message')"
,尝试这样的事情:
def TestCommand():
m.showinfo('title', 'message')
class Gui:
def __init__(self):
pass
def newButton(self, val, command=TestCommand):
self.b=tk.Button(std.root, text=val, command=command).pack()
请记住,Button 构造函数采用 函数 作为命令参数,而不是字符串。