[英]How to make a window with buttons in python
如何創建一個函數來創建一個帶有兩個按鈕的窗口,其中每個按鈕都有一個指定的字符串,如果單擊,則返回一個指定的變量? 類似於此視頻中的@ 3:05 https://www.khanacademy.org/science/computer-science-subject/computer-science/v/writing-a-simple-factorial-program---python-2 (我知道這是一個非常簡單的初學者程序的教程,但它是我能找到的唯一視頻)但沒有文本框,而且我對“確定”和“取消”按鈕的作用有更多的控制。
我是否必須創建一個窗口,在其中繪制一個帶有字符串的矩形,然后創建一個循環來檢查鼠標移動/鼠標點擊,然后在鼠標坐標位於其中一個按鈕內時返回一些東西,並且鼠標被點擊了? 或者是否有一個功能/一組功能可以使帶有按鈕的窗口更容易? 還是模塊?
概述
不,您不必“繪制矩形,然后進行循環”。 你將需要做的是進口某種形式的GUI工具包,並使用方法和對象的內置到該工具包。 一般來說,其中一種方法是運行一個循環,該循環偵聽事件並根據這些事件調用函數。 這個循環稱為事件循環。 因此,雖然必須運行這樣的循環,但您不必創建循環。
注意事項
如果您希望從提示(例如您鏈接到的視頻)中打開一個窗口,則問題會更棘手一些。 這些工具包並非旨在以這種方式使用。 通常,您編寫一個完整的基於 GUI 的程序,其中所有輸入和輸出都通過小部件完成。 這並非不可能,但在我看來,學習時應該堅持使用所有文本或所有 GUI,而不是將兩者混合。
使用 Tkinter 的示例
例如,一個這樣的工具包是 tkinter。 Tkinter 是 Python 內置的工具包。 任何其他工具包(例如 wxPython、PyQT 等)都非常相似,並且也能正常工作。 Tkinter 的優勢在於您可能已經擁有它,它是學習 GUI 編程的絕佳工具包。 這對於更高級的編程也很棒,盡管您會發現有人不同意這一點。 不要聽他們的。
這是 Tkinter 中的一個示例。 此示例適用於 python 2.x。 對於 python 3.x,您需要從tkinter
而不是Tkinter
導入。
import Tkinter as tk
class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
# create a prompt, an input box, an output label,
# and a button to do the computation
self.prompt = tk.Label(self, text="Enter a number:", anchor="w")
self.entry = tk.Entry(self)
self.submit = tk.Button(self, text="Submit", command = self.calculate)
self.output = tk.Label(self, text="")
# lay the widgets out on the screen.
self.prompt.pack(side="top", fill="x")
self.entry.pack(side="top", fill="x", padx=20)
self.output.pack(side="top", fill="x", expand=True)
self.submit.pack(side="right")
def calculate(self):
# get the value from the input widget, convert
# it to an int, and do a calculation
try:
i = int(self.entry.get())
result = "%s*2=%s" % (i, i*2)
except ValueError:
result = "Please enter digits only"
# set the output widget to have our result
self.output.configure(text=result)
# if this is run as a program (versus being imported),
# create a root window and an instance of our example,
# then start the event loop
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(fill="both", expand=True)
root.mainloop()
這是我的部分。 我正在制作一個人工智能聊天機器人,只是在登錄和勾畫東西的界面上工作。 我也是 .json 的初學者,所以這有助於我學習。
也許我也會解釋一下。
首先,創建一個
.json
文件,命名為您喜歡的任何名稱。 確保文件與代碼位於同一目錄路徑/文件夾中,或者您可以導入 os 來執行此操作。
接下來導入 Tkinter。 它可能是也可能不是內置模塊,但請嘗試並查看。 還導入 JSON,時間不是必需的,但可以提供幫助。
import tkinter as tk
import json
import time
接下來,為所有這些發生創建一個窗口。 如有必要,編輯信息。
app = tk.Tk()
app.wm_title("Sign Up or Log in")
app.geometry("500x300")
如果需要,請添加標簽。
k = tk.Label(text = "Hello there, I'm Lola! We'll talk soon. Just let me know your credentials!\nJust click on sign up below so that I can identify you!", justify="left")
k.pack()
添加一個按鈕供用戶單擊。
sign_in = tk.Button(text="Sign Up or Log In", command=signin)
sign_in.pack()
我們需要為按鈕定義上面使用的簽名函數。 所以在我們創建按鈕之前,我們先定義它。 有點長,所以我只解釋一般部分。 在我們檢查之前,我們首先獲取他們的詳細信息
def signin():
em = tk.Label(text="Email:")
em.pack()
en1 = tk.Entry(width=50)
en1.pack()
pa = tk.Label(text="Password:")
pa.pack()
en2 = tk.Entry(width=50)
en2.pack()
na = tk.Label(text="Name:")
na.pack()
en3 = tk.Entry(width=50)
en3.pack()
接下來,讓我們定義提交函數並創建按鈕。 這就是 json 的用武之地。我們首先獲取詳細信息並將它們存儲在像這樣的變量中。
def submit():
email = str(en1.get())
password = str(en2.get())
name = str(en3.get())
login = tk.Label(text="")
然后,我們不應該忘記先讀取json文件
with open("info.json", "r") as f:
users = json.load(f)
現在讓我們做檢查
if email in users:
login.config(text="You already have an account! Click log in please!")
loginn = tk.Button(text = "Log in", command = login)
else:
users[email] = {}
users[email]["Password"] = password
users[email]["Name"] = name
with open("info.json", "w") as f:
json.dump(users, f)
login.config(text=f"You've successfully created an account. Just click on log in below! Credentials:\nEmail: {email}\nPassword: {password}\nName: {name}")
login.pack()
現在,我們將定義登錄。 一切都非常相似
def loggin():
email = str(en1.get())
password = str(en2.get())
name = str(en3.get())
login = tk.Label(text="")
with open("info.json", "r") as f:
users = json.load(f)
if not email in users:
login.config(text="You don't have an account, sign up instead!")
else:
passs = users[email]["Password"]
if password != passs:
login.config(text="Wrong credentials. It doesn't match what I've recorded")
else:
login.config(text="Success! You've logged in. Please wait, as the software is still in the early stage of development.\nYou might have to sign up again later. I'll let you know soon.")
login.pack()
loginn = tk.Button(text = "Log in", command = loggin)
loginn.pack()
最后,這一行代碼將確定是否一切正常。 確保將其放在最后的代碼中。
window.mainloop()
這就是結束,請不要復制這個,我工作了 5 個小時來理解這一點。 我是一個初學者,就像其他人一樣,但請不要復制此。 舉個例子來理解。 即使你這樣做,請給予信任。 但大多數情況下,不要。
#Creating a GUI for entering name
def xyz():
global a
print a.get()
from Tkinter import *
root=Tk() #It is just a holder
Label(root,text="ENter your name").grid(row=0,column=0) #Creating label
a=Entry(root) #creating entry box
a.grid(row=7,column=8)
Button(root,text="OK",command=xyz).grid(row=1,column=1)
root.mainloop() #important for closing th root=Tk()
這是最基本的。
tkinter 是一個 GUI 庫,這段代碼創建了簡單的無文本按鈕:
import tkinter as tk
class Callback:
def __init__(self, color):
self.color = color
def changeColor(self):
print('turn', self.color)
c1 = Callback('blue')
c2 = Callback('yellow')
B1 = tk.Button(command=c1.changeColor)
B2 = tk.Button(command=c2.changeColor)
B1.pack()
B2.pack()
這是我的方法,創建一個帶有名為“Hello!”的按鈕的窗口。 當它關閉時,一個新窗口打開,“酷!”
from tkinter import *
def hello(event):
print("Single Click, Button-l")
def Cool(event):
print("That's cool!")
widget = Button(None, text='Hello!')
widget.pack()
widget.bind('<Button-1>', Hello)
widget.mainloop()
widget = Button(None, text='Cool!')
widget.pack()
widget.bind('<Double-1>', Cool)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.