我正在尝试使用tkinter和ttk创建一个窗口。当我在Windows 7 Pro PC上运行脚本时,我得到的错误是没有名为ttk的模块,但是当我查看我的PC时,我看到了模块。这个确切的脚本也适用于我的RPi没有问题。我究竟做错了什么?我是否需要重新安装ttk,若然,怎么做?
try:
import tkinter as tk
from tkinter import *
except:
import Tkinter as tk
from Tkinter import *
import ttk
class MainWindow(tk.Frame):
def __init__(self, master):
self.master = master
tk.Frame.__init__(self,master)
tk.Label(self, text = 'Hi').grid(row = 1, column = 1)
tk.Button(self, text = 'Button 1', width = 10, fg = 'red', command = self.button).grid(row = 2, column = 1)
self.grid()
def button(self):
print('Yo')
if __name__ == '__main__':
root = tk.Tk()
MainWindow(root)
root.mainloop
答案 0 :(得分:0)
对于Python3,导入ttk的方法如下
from tkinter import ttk
或者
from tkinter import *
from tkinter.ttk import *
覆盖tkinter基本小部件。
对于Python 2
import ttk
或者
from Tkinter import *
from ttk import *
是记录在案的方法。
如果这些都不起作用,则表明安装有问题。
(如果您使用的是Python 2.7,请开始使用Python 3,Python 2 is almost end of life)。
答案 1 :(得分:0)
更新
所以我看到你的程序有几个问题。
请记住tkinter和ttk在Windows版本上默认带有python。你不应该重新安装tkinter。如果您的python出现问题,那么您应该重新安装python。
此处的问题不是ttk
导入,而是mainloop
您必须使用()
调用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.
更新
你在评论中的问题:
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()
控制台结果:
orange
通过为我们正在创建对象的类命名,我们可以从类外部与其属性进行交互。
我们还可以从类外部更改对象的属性。如果您要将此行MyApp.root.config(bg = "blue")
添加到示例中,您将看到窗口更改为蓝色。