2017-10-22 95 views
0

所以我在Python中編程語言。
這是我到目前爲止的代碼:Tkinter非常奇怪

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的命令沒有運行。
我也嘗試過使用
它只是不工作!
你能告訴我爲什麼發生這種情況,以及如何解決它?

謝謝!

回答

3

問題是,您正試圖傳遞一個字符串作爲命令而不是函數。取而代之的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() 

記住按鈕構造函數採用功能作爲命令的參數,而不是一個字符串。

+0

哦,好吧......哦...... IM DUMB! :P我用了一個字符串而不是lambda! – o0000000000000000000000000000o