更新:
所以我看到你的程序有几个问题。
请记住tkinter和ttk默认在Windows版本中带有python。你不应该重新安装tkinter。如果你的python有问题,那么你应该重新安装python。
这里的问题不是ttk
进口,但mainloop
您必须()
调用主循环这么做mainloop()
代替。
如果你只改变root.mainloop
到root.mainloop()
你的程序将在Python 2
工作,但也有几件事情错了你的计划。
看看下面的例子:
try:
# Python 3.x
import tkinter as tk
from tkinter import ttk #this is how we import for Python 3.x
except:
# Python 2.x
import Tkinter as tk
import ttk # this needs to be inside the except: not outside like you had it.
# this is because if you were to move to python 3 with this it would not work and cause an error.
class MainWindow(tk.Frame):
# I added in the *args and ** kwargs to show what a full class __init__ can accept.
def __init__(self, master, *args, **kwargs):
tk.Frame.__init__(self, master, *args, **kwargs)
self.master = master
# for your label and button you need to set it as a variable.
self.my_label = tk.Label(self.master, text = 'Hi').grid(row = 1, column = 1)
self.my_button = tk.Button(self.master, text = 'Button 1', width = 10, fg = 'red', command = self.button).grid(row = 2, column = 1)
def button(self):
print'Yo'
# print('Yo') # python 3
if __name__ == "__main__":
root = tk.Tk()
app = MainWindow(root) # you should define your main window as something. This way you can interact with the object from outside.
tk.mainloop() # this must be called in order to tkinter to work.
更新:
按照您在评论中质疑:通过给
orange
:
import tkinter as tk
class MintApp(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.root = parent
self.py_frame_color = "orange" # this is an attribute
self.root.config(bg = self.py_frame_color)
if __name__ == "__main__":
root = tk.Tk()
MyApp = MintApp(root)
print(MyApp.root.cget('bg'))
tk.mainloop()
控制台结果名字我们正在创建一个对象,我们可以与其他类的属性进行交互。
我们还可以从类的外部更改对象的属性。如果您要将此行MyApp.root.config(bg = "blue")
添加到示例中,您将看到窗口变为蓝色。
我已经更新了我的答案,以解释在程序中导致问题的原因,我也对发布的代码进行了一些更改并解释了一些内容。 –
你运行python 2或3吗?这两种版本导入ttk的方式不同。 –