2013-05-08 106 views
0

我寫這個基本Tk的程序,可以打開文本文件,但我似乎可以得到它的工作從一個函數使用一個變量的函數外

這裏是我的代碼:

from Tkinter import * 
from tkFileDialog import askopenfilename 
def openfile(): 
    filename = askopenfilename(parent=root) 
    f = open(filename) 
    x = f.read() 
    return x 


root = Tk() 
menubar = Menu(root) 
filemenu = Menu(menubar, tearoff=0) 
filemenu.add_command(label="Open", command=openfile) 
filemenu.add_separator() 
filemenu.add_command(label="Exit", command=root.quit) 
menubar.add_cascade(label="File", menu=filemenu) 


text = Text(root) 
text.insert(INSERT,(x)) 

text.pack() 

root.config(menu=menubar) 
root.mainloop() 

我嘗試輸入x進入我的tk窗口,但它的俗語說它沒有定義,即使我返回x

爲什麼不工作im確定它的東西很容易,但我不能弄明白!

回答

3

所以你有兩個相關的問題在這裏。

  1. 你想,即使你還沒有定義爲使用x
  2. 返回從openfile東西不會在這種情況下工作,因爲你不能把它設置爲另一個變量(如x

您可能想要做的是讀取該文件並將其插入Text小部件中,所有這些都在同一個函數調用中。嘗試這樣的事情,

from Tkinter import * 
from tkFileDialog import askopenfilename 

def openfile(): 
    filename = askopenfilename(parent=root) 
    f = open(filename) 
    x = f.read() 
    text.insert(INSERT,(x,)) 

root = Tk() 
menubar = Menu(root) 
filemenu = Menu(menubar, tearoff=0) 
filemenu.add_command(label="Open", command=openfile) 
filemenu.add_separator() 
filemenu.add_command(label="Exit", command=root.quit) 
menubar.add_cascade(label="File", menu=filemenu) 

text = Text(root) 
text.pack() 

root.config(menu=menubar) 
root.mainloop() 
+0

作品正是我想要的完美謝謝! – Serial 2013-05-08 02:50:24

1

當你從一個函數返回一個值,你需要將其分配給一個變量,像這樣():

myVariable = openfile() 

然後你就可以在你的參數使用這個變量爲:

text.insert(INSERT, (myVariable)) 

變量x在函數內定義,因此超出範圍。

+0

當我做這種方式,當我運行GUI它只是打開了文件,而不是對話框打開GUI然後等待用戶點擊打開 – Serial 2013-05-08 02:25:31

+0

@ChristianCareaga不要有蟒蛇在這臺電腦上,或者我會檢查你的代碼。抱歉。 – 2013-05-08 02:34:19

+1

我知道了!謝謝! – Serial 2013-05-08 02:35:35

相關問題