国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

[翻譯]一個簡單實用的Python Tkinter教程

Noodles / 1241人閱讀

摘要:輸入框和標簽都帶了一個神秘的參數。我們可以在之前調用的時候做這些事,但上面這樣做也是個不錯的選擇第二行告訴讓我們的輸入框獲取到焦點。

原文http://www.tkdocs.com/tutorial/firstexample.html

第一個實用的簡易案例

A First (Real) Example
With that out of the way, let"s try a slightly more useful example, which will give you an initial feel for what the code behind a Tk program looks like.
我們試著做個稍微實用的例子,通過這種方式,讓你感受一下Tk的程序代碼是什么樣的

Design
設計
The example we"ll use is a simple GUI tool that will convert a number of feet to the equivalent number of meters. If we were to sketch this out, it might look something like this:我們將用簡單的GUI工具來創建這個例子。他能把英尺轉換為公尺。如果我們畫了草圖,那他看起來應該是這個樣子:

A sketch of our feet to meters conversion program.

我們的英尺轉公尺程序的草圖

So it looks like we have a short text entry widget that will let us type in the number of feet, and a "Calculate" button that will get the value out of that entry, perform the calculation, and then put the resulting number of meters on the screen just below where the entry is. We"ve also got three static labels ("feet", "is equivalent to", and "meters") which help our user figure out how to use the interface.

看起來我們需要一個文本輸入框來輸入英尺,一個“Calculate”按鈕來取得文本框的值并執行計算,在輸入框下方輸出轉換后的值,我們同樣需要3個標簽 ("feet", "is equivalent to", 和 "meters") 幫助用戶理解怎么用

In terms of layout, things seem to naturally divide into three columns and three rows:
布局方面,我們可以設計成3行3列的形式

The layout of our user interface, which follows a 3 x 3 grid.
我們界面的布局,一個3x3的網格

Code
代碼
Now here is the Python code to create thie program.
下面是這程序Python代碼(譯注:這是python3的代碼,python2中有稍許不同,下面會提到)

from tkinter import *
from tkinter import ttk
def calculate(*args):
    try:
        value = float(feet.get())
        meters.set((0.3048 * value * 10000.0 + 0.5)/10000.0)
    except ValueError:
        pass
    
root = Tk()
root.title("Feet to Meters")
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)
feet = StringVar()
meters = StringVar()
feet_entry = ttk.Entry(mainframe, width=7, textvariable=feet)
feet_entry.grid(column=2, row=1, sticky=(W, E))
ttk.Label(mainframe, textvariable=meters).grid(column=2, row=2, sticky=(W, E))
ttk.Button(mainframe, text="Calculate", command=calculate).grid(column=3, row=3, sticky=W)
ttk.Label(mainframe, text="feet").grid(column=3, row=1, sticky=W)
ttk.Label(mainframe, text="is equivalent to").grid(column=1, row=2, sticky=E)
ttk.Label(mainframe, text="meters").grid(column=3, row=2, sticky=W)
for child in mainframe.winfo_children():child.grid_configure(padx=5, pady=5)
feet_entry.focus()
root.bind("", calculate)
root.mainloop()

And the resulting user interface:

Screenshot of our completed feet to meters user interface (on Mac OS X, Windows and Linux).
程序運行的截圖

Step-by-Step Walkthrough
分步演練
Let"s take a closer look at that code, piece by piece. For now, all we"re trying to do is get a basic understanding of the types of things we need to do to create a user interface in Tk, and roughly what those things look like. We"ll go into details later.
讓我們看看這些代碼,一點點來,現在我們要做的事情是,對我們要創建一個Tk界面有一個基本理解并知道他大概是什么樣的,稍后我們來講講細節.

Python3代碼:

from tkinter import *
from tkinter import ttk

Python2代碼:

from Tkinter import *
import ttk #python2中ttk是獨立的模塊

These two lines tell Python that our program needs two modules. The first,?"tkinter", is the standard binding to Tk, which when loaded also causes the existing Tk library on your system to be loaded. The second,?"ttk", is Python"s binding to the newer "themed widgets" that were added to Tk in 8.5.
這兩行代碼告訴Python我們的程序需要兩個模塊,第一個是tkinter,這個Tk所必須的,導入這個模塊時你系統中的Tk相關庫也會同時被加載。第二個是ttk,這是Tk 8.5版本后新增的主題控件(譯注:關于python中Tk的版本??梢栽趯雝kinter模塊后執行tkinter.Tcl().eval("info patchlevel")或者Tkinter.Tcl().eval("info patchlevel")查看版本,前者是python2,后者是pyhton3。Tk在從python2遷移到python3時把名字從Tkinter改成了tkinter)

tips:
提示:
Notice that we"ve imported everything from the tkinter module, so that we can call tkinter functions etc. without prefixing them, which is standard Tkinter practice. However, because we"ve imported just "ttk" itself, that means we"ll need to prefix anything inside that module. So for example calling "Entry(...)" would invoke the function inside the tkinter module, while we"d need "ttk.Entry(...)" to invoke the function inside ttk. As you"ll see, several functions are defined in both modules, and sometimes you will need both, depending on the context. Making the ttk calls explicit facilitates this, and will be the style used in this tutorial.
注意,我們導入了tkinter所有的模塊,所以我們可以直接使用tkinter的所有功能,這是Tkinter的標準做法,然而,我們在后面導入了ttk,這意味著我們接下來要用到的組件前面都得加前綴,舉個例子,直接調用“Entry”會調用tkinter內部的模塊,然而我們需要的是ttk里的“Entry”,所以要用“ttk.Enter”,如你所見,許多函數在兩者之中都有,如果同時用到這兩個模塊,你需要根據整體代碼選擇用哪個模塊,讓ttk的調用更加清晰,本教程中也會使用這種風格

root = Tk()
root.title("Feet to Meters")
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)    

FYI:Yes, the?"calculate"?function appeared before this. We"ll describe it down below, but need to include it near the start because we reference it in other parts of the program.
僅供參考:沒錯 ,“calculate"方法在這之前定義了,我們稍后在討論他,但需要先在開始的地方定義好,因為之后我們會在其他地方調用到它

Next, the above lines set up the main window, giving it the title "Feet to Meters". Next, we create a frame widget, which will hold all the content of our user interface, and place that in our main window. The?"columnconfigure"/"rowconfigure"?bits just tell Tk that if the main window is resized, the frame should expand to take up the extra space.
接下來,上面的那些代碼創建了主窗口,設置窗口的標題為“Feet to Meters”,然后,我們創建了一個frame控件,用戶界面上的所有東西都包含在里面,并且放在主窗口中。columnconfigure"/"rowconfigure是告訴Tk如果主窗口的大小被調整,frame空間的大小也隨之調整

feet = StringVar()
meters = StringVar()
feet_entry = ttk.Entry(mainframe, width=7, textvariable=feet)
feet_entry.grid(column=2, row=1, sticky=(W, E))
ttk.Label(mainframe, textvariable=meters).grid(column=2, row=2, sticky=(W, E))
ttk.Button(mainframe, text="Calculate", command=calculate).grid(column=3, row=3, sticky=W)

FYI:
Strictly speaking, we could just put the other parts of our interface directly into the main root window, without the intervening content frame. However, the main window isn"t itself part of the "themed" widgets, so its background color wouldn"t match the themed widgets we will put inside it. Using a "themed" frame widget to hold the content ensures that the background is correct.
僅供參考:嚴格來講,我們要做的僅僅是把其他控件直接塞進主窗口中就行,不需要使用frame空間。然而,主窗口自身并不是“帶主題”的控件的一部分,所以如果我們把“帶主題”的控件放入主窗口,他的背景顏色不能和“帶主題”的控件相匹配。用一個frame控件可以使得“帶主題”的控件和主窗口的背景相匹配

The preceding lines create the three main widgets in our program: the entry where we type the number of feet in, a label where we put the resulting number of meters, and the calculate button that we press to perform the calculation.

上面的那幾行代碼為我們的程序創建了3個主要的控件:用來輸入英尺的輸入框,一個用來輸出轉換成米單位結果的標簽,和一個執行計算的計算按鈕

For each of the three widgets, we need to do two things: create the widget itself, and then place it onscreen. All three widgets, which are "children" of our content window are created as instances of one of Tk"s themed widget classes. At the same time as we create them, we give them certain options, such as how wide the entry is, the text to put inside the Button, etc. The entry and label each are assigned a mysterious?"textvariable"; we"ll see what that does shortly.

關于這三個控件,我們要做的就兩件事:創建,顯示。這三個控件都是窗口的“孩子”,“帶主題”控件的類的實例。同時我們為他們設置一些選項,比如輸入的寬度,按鈕顯示的文本等等。輸入框和標簽都帶了一個神秘的參數“textvariable”。我們不久后還會再看到他

If the widgets are just created, they won"t automatically show up on screen, because Tk doesn"t know how you want them to be placed relative to other widgets. That"s what the?"grid"?part does. Remembering the layout grid for our application, we place each widget in the appropriate column (1, 2 or 3), and row (also 1, 2 or 3). The?"sticky"?option says how the widget would line up within the grid cell, using compass directions. So?"w"?(west) means anchor the widget to the left side of the cell,?"we"(west-east) means anchor it to both the left and right sides, and so on.
如果控件僅僅被創建了,他們是不會自動顯示在屏幕上的,因為Tk并不知道這些控件和其他控件的位置關系。那是“grid”那個部分要做的事情。還記得我們程序的網格布局么?我們把每個控件放到對應行或者列中,”sticky“選項指明控件在網格單元中的排列,用的是指南針方向。所以“w”代表固定這個控件在左邊的網格中。
“we”代表固定這個空間在左右之間。等等

ttk.Label(mainframe, text="feet").grid(column=3, row=1, sticky=W)
ttk.Label(mainframe, text="is equivalent to").grid(column=1, row=2, sticky=E)
ttk.Label(mainframe, text="meters").grid(column=3, row=2, sticky=W)

The above three lines do exactly the same thing for the three static text labels in our user interface; create each one, and place it onscreen in the appropriate cell in the grid.
上面這三行明確的為三個靜態標簽做了一點小工作:創建,然后放在適合的網格位置中

for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)
feet_entry.focus()
root.bind("", calculate)

The preceding three lines help put some nice finishing touches on our user interface.
這三行在界面上做了一些漂亮的收尾工作

The first line walks through all of the widgets that are children of our content frame, and adds a little bit of padding around each, so they aren"t so scrunched together. We could have added these options to each?"grid"?call when we first put the widgets onscreen, but this is a nice shortcut.
第一行處理了frame中的所有控件,并且為每個空間四周添加了一些空隙,不會顯得揉成一團。我們可以在之前調用grid的時候做這些事,但上面這樣做也是個不錯的選擇

The second line tells Tk to put the focus on our entry widget. That way the cursor will start in that field, so the user doesn"t have to click in it before starting to type.
第二行告訴Tk讓我們的輸入框獲取到焦點。這方法可以讓光標一開始就在輸入框的位置,用戶就可以不用再去點擊了

The third line tells Tk that if the user presses the Return key (Enter on Windows) anywhere within the root window, that it should call our calculate routine, the same as if the user pressed the Calculate button.
第三行告訴Tk如果用戶在窗口中按下了回車鍵,就執行計算,等同于用戶按下了計算按鈕

def calculate(*args):
try:
    value = float(feet.get())
    meters.set((0.3048 * value * 10000.0 + 0.5)/10000.0)
except ValueError:
    pass

Here we define our calculate procedure, which is called either when the user presses the Calculate button, or hits the Return key. It performs the feet to meters calculation, taking the number of feet from our entry widget, and placing the result in our label widget.
這里我們定義了計算過程,無論是按回車還是點計算按鈕,他都會從輸入框中取得把英尺,轉換成米,然后輸出到標簽中

Say what? It doesn"t look like we"re doing anything with those widgets! Here"s where the magic"textvariable"?options we specified when creating the widgets come into play. We specified the global variable "feet" as the textvariable for the entry, which means that anytime the entry changes, Tk will automatically?update the global variable feet. Similarly, if we explicitly change the value of a textvariable associated with a widget (as we"re doing for "meters" which is attached to our label), the widget will automatically be updated with the current contents of the variable. Slick.
怎么樣,他看起來和前面那些控件完全不一樣,之前定義的那個魔術般的“textvariable”選項,在這里開始發揮作用,我們指定了全局變量“feet”成為一個textvariable來接受輸入的內容,這意味著任何時候輸入的值被改變,Tk都會自動的改變“feet”這個全局變量的值,同樣的,如果我們明確改變了一個textvariable相關聯的的控件的值(類似我們改變meters變量就改變了標簽一樣),控件會自動更新相應的變量。

root.mainloop()

This final line tells Tk to enter its event loop, which is needed to make everything run.
最后一行是告訴Tk進入事件循環,這是讓程序能運行所必須的

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/44213.html

相關文章

  • [譯][Tkinter 教程11] 對話框和消息框

    摘要:已獲原作者授權原系列地址簡介提供了一系列的對話框可以用來顯示文本消息提示警告信息和錯誤信息選擇文件或顏色其他一些簡單的對話框還可以請求用戶輸入文本整數或數字下面是一個典型的對話框使用場景在應用程序中經常會有退出按鈕如下點擊按鈕會彈出一個確認 已獲原作者授權. 原系列地址: Python Tkinter 簡介 Tkinter 提供了一系列的對話框, 可以用來顯示文本消息, 提示警告信息...

    Anchorer 評論0 收藏0
  • [譯][Tkinter 教程13] Mastermind 游戲

    摘要:已獲原作者授權原系列地址游戲本章我們演示一個進階例子我們用編寫了游戲這個游戲也被稱作或者或者是一個古老的益智解謎游戲由兩名玩家參與早在世紀人們就在用鉛筆和紙來玩這個游戲了在年發明的游戲正是受到這個游戲的啟發和在基本理念上是一樣的但被盒裝出售 已獲原作者授權. 原系列地址: Python Tkinter Mastermind 游戲 本章我們演示一個進階例子. 我們用 Tkinter 編...

    Jaden 評論0 收藏0
  • [譯][Tkinter 教程01] 入門: Label 控件

    摘要:已獲原作者授權原系列地址下面我們將以中最簡單的控件控件開始這個系列的教程在中控件用以顯示文字和圖片通常被用來展示信息而非與用戶交互譯者注也可以綁定點擊等事件只是通常不這么用程序員的教程怎么能少了我們尊重這個傳統但我們不說讓我們來秀出吧下面的 已獲原作者授權. 原系列地址: Python Tkinter Hello Tkinter Label 下面我們將以 Tkinter 中最簡單的控...

    Sike 評論0 收藏0
  • [譯][Tinkter 教程05] Radiobutton 控件

    摘要:已獲原作者授權原系列地址單選按鈕是一種可在多個預先定義的選項中選擇出一項的控件單選按鈕可顯示文字或圖片顯示文字時只能使用預設字體該控件可以綁定一個函數或方法當單選按鈕被選擇時該函數或方法將被調用單選按鈕這個名字來源于收音機上的調頻按鈕這些按 已獲原作者授權. 原系列地址: Python Tkinter Radio Buttons 單選按鈕是一種可在多個預先定義的選項中選擇出一項的 T...

    shusen 評論0 收藏0
  • [譯][Tkinter 教程06] Checkbox 控件

    摘要:已獲原作者授權原系列地址簡介控件允許用戶在多個選項中選擇多項則只允許用戶選擇一項通常會顯示為一個空白的方框表示未被選中或者方框中有一個對號或號表示被選中一個對該選項的簡短描述會和選擇框一同顯示的狀態會因點擊而改變這個點擊可能來自鼠標也可能來 已獲原作者授權. 原系列地址: Python Tkinter 簡介 Checkbox 控件允許用戶在多個選項中選擇多項. Radiobutton...

    RyanHoo 評論0 收藏0

發表評論

0條評論

Noodles

|高級講師

TA的文章

閱讀更多
最新活動
閱讀需要支付1元查看
<