Tkinter(2.x 與3.X的區別)

夢書發表於2013-10-18

1.包的引入

2.X下是

from Tkinter import *

而3.x是

from tkinter import *

否則,會報找不到tkinter的錯誤

Traceback (most recent call last):
  File "read_data_from_gui.py", line 1, in <module>
    from tkinter import *
ImportError: No module named tkinter

 2.訊息框

 1 # 2.X version
 2 from Tkinter import *
 3 import tkMessageBox
 4 
 5 def save_data():
 6     try:
 7         fileD = open("deliveries.txt", "a")    
 8         fileD.write("Depot:\n") 
 9         fileD.write("%s\n" % depot.get()) 
10         fileD.write("Description:\n") 
11         fileD.write("%s\n" % description.get()) 
12         fileD.write("Address:\n") 
13         fileD.write("%s\n" % address.get("1.0", END)) 
14         depot.set(None) 
15         description.delete(0, END) 
16         description.delete(0, END) 
17         address.delete("1.0", END) 
18     except Exception as ex:
19         tkMessageBox.showerror("Error!", "Can't write to the file\n %s" % ex)
20 
21 
22 #3.x version
23 from tkinter import *
24 import tkinter.messagebox
25 
26 
27 def save_data():
28     try:
29         fileD = open("deliveries.txt", "a")    
30         fileD.write("Depot:\n") 
31         fileD.write("%s\n" % depot.get()) 
32         fileD.write("Description:\n") 
33         fileD.write("%s\n" % description.get()) 
34         fileD.write("Address:\n") 
35         fileD.write("%s\n" % address.get("1.0", END)) 
36         depot.set(None) 
37         description.delete(0, END) 
38         description.delete(0, END) 
39         address.delete("1.0", END) 
40     except Exception as ex:
41         tkinter.messagebox.showerror("Error!", "Can't write to the file\n %s" % ex)

 

相關文章