2012-05-20 46 views
3

我正在構建一個小型教育應用程序。使用tk獲取文本的窗口

我已經完成了所有的代碼,我所缺少的一切都是讓窗口打開並顯示文本框,圖像和按鈕的TK。

它應該做的所有事情,它在單擊按鈕並關閉窗口後返回插入到文本框中的文本。

那麼,我該怎麼做?

我一直在看代碼,但沒有任何工作,我幾乎感到羞恥,因爲這是如此基本。

謝謝

+0

的應用程序是一個命令行之一:如何讓圖像http://effbot.org/tkinterbook/entry.htm

參考? – jadkik94

+1

您是否有任何代碼示例,您已經使用Tk嘗試過,因此社區可以看到可能出錯的內容? – jdi

+0

我很高興地說我沒有搬到PySide,並學會了如何使用它。這一切現在看起來更容易。 –

回答

2

一個簡單的編寫GUI的方法是使用Tkinter。有與文本和一個按鈕顯示窗口的例子:

from Tkinter import* 

class GUI: 

    def __init__(self,v): 

     self.entry = Entry(v) 
     self.entry.pack() 

     self.button=Button(v, text="Press the button",command=self.pressButton) 
     self.button.pack() 

     self.t = StringVar() 
     self.t.set("You wrote: ") 
     self.label=Label(v, textvariable=self.t) 
     self.label.pack() 

     self.n = 0 

    def pressButton(self): 

     text = self.entry.get() 
     self.t.set("You wrote: "+text) 

w=Tk() 
gui=GUI(w) 
w.mainloop() 

你可以看看在Tkinter的文檔,標籤控件還支持包括圖片。

問候

+0

如果你想返回文本,那麼在pressButton方法中,你可以退出窗口然後返回文本。 – Carlos

+0

用你的回覆來構造我需要的東西!謝謝! –

2

enter image description here

這是一個簡單的代碼,您可以通過inputBox輸入到myText。它應該讓你開始正確的方向。根據你需要檢查或做什麼,你可以添加更多的功能。注意你可能不得不玩弄image = tk.PhotoImage(data=b64_data)這一行的順序。因爲如果你把它放在b64_data = ...之後。它會給你錯誤。 (我使用Python 3.2運行MAC 10.6)。此圖片僅適用於GIF。如果您想了解更多信息,請參閱底部的參考資料。

import tkinter as tk 
import urllib.request 
import base64 

# Download the image using urllib 
URL = "http://www.contentmanagement365.com/Content/Exhibition6/Files/369a0147-0853-4bb0-85ff-c1beda37c3db/apple_logo_50x50.gif" 

u = urllib.request.urlopen(URL) 
raw_data = u.read() 
u.close() 

b64_data = base64.encodestring(raw_data) 

# The string you want to returned is somewhere outside 
myText = 'empty' 

def getText(): 
    global myText 
    # You can perform check on some condition if you want to 
    # If it is okay, then store the value, and exist 
    myText = inputBox.get() 
    print('User Entered:', myText) 
    root.destroy() 

root = tk.Tk() 

# Just a simple title 
simpleTitle = tk.Label(root) 
simpleTitle['text'] = 'Please enter your input here' 
simpleTitle.pack() 

# The image (but in the label widget) 
image = tk.PhotoImage(data=b64_data) 
imageLabel = tk.Label(image=image) 
imageLabel.pack() 

# The entry box widget 
inputBox = tk.Entry(root) 
inputBox.pack() 

# The button widget 
button = tk.Button(root, text='Submit', command=getText) 
button.pack() 

tk.mainloop() 

下面是引用,如果你想知道更多關於Tkinter的Entry控件:Stackoverflow Question

+0

這工作完美,謝謝! –