當前應用
我圈出來的是我不能移動的東西,即使我的側面是右邊而不是底部。 
這是代碼中的標簽 
我有一個非常簡單的用于重量轉換器的 python 代碼,我想將答案附加到框架上,以便它位于輸入框下方。我不會貼在那里,只會貼在頂部或底部。按鈕也是如此,我可以在頂部或底部以外的任何地方附加任何東西。對不起,如果其中一些沒有意義,我對 python 很陌生。
import tkinter as tk
from tkinter.constants import BOTTOM
from typing import Text
root = tk.Tk()
root.resizable(False, False)
root.title('Weight Converter')
canvas = tk.Canvas(root, height=300, width=300, bg='teal')
frame=tk.Frame(root)
frame.place(relwidth=0.8, relheight=0.8, relx=0.1, rely=0.1)
labelanswer=tk.Label(frame, bg='white')
labelanswer.place(x=105, y=90)
def to_kg():
pound = float(entry1.get())*2.20462
labelanswer['text'] = pound
def from_kg():
kg=float(entry1.get())/2.20462
labelanswer['text'] = kg
entry1 = tk.Entry (root)
canvas.create_window(200, 200, window=entry1)
entry1.place(x=95, y=90)
labeltext=tk.Label(root, text="Weight Converter", bg='white')
labeltext.pack()
b1 = tk.Button(root, text="to kg", bg='white', command=to_kg)
b2=tk.Button(root, text='from kg', command=from_kg, bg='white')
labelanswer.pack()
b2.pack(side=BOTTOM)
b1.pack(side=BOTTOM)
canvas.pack()
frame.pack()
root.mainloop()
uj5u.com熱心網友回復:
您必須對按鈕和 labelAnswer 執行與為條目所做的相同的操作。
canvas.create_window(window=YOUR WIDGET HERE)
但是,您可以使用以下命令一起洗掉畫布:
root.geometry('300x300')
root.config(bg = 'teal')
geometry() 接受一個字串 'WIDTH x HEIGHT' 并將相應地設定小部件。
config() 將允許您在創建后更改大多數小部件的屬性。在上面的例子中,我們將背景顏色 (bg) 更改為藍綠色
這允許您洗掉所有畫布絨毛并使代碼更具可讀性
您也可以在創建物件時使用 bg 選項。
labelText = tk.Label(root, text = "Weight Converter", bg = 'teal')
您也可以使用字串代替內置常量,無論是否是我留給社區的最佳選擇。但我建議 tk.BOTTOM 或 'bottom' 而不是僅僅匯入常量,因為它只會增加絨毛。
我經歷并清理了一些東西,但這就是我最終得到的:
import tkinter as tk
def to_kg():
pound = float(entry.get())*2.20462
labelAnswer['text'] = pound
def to_pounds():
kg=float(entry.get())/2.20462
labelAnswer['text'] = kg
# Creating root window
root = tk.Tk()
# geometery() allows you to set the width and hieght of a window with a string 'WIDTH x HIEGHT'
root.geometry('300x300')
root.resizable(False, False)
# There are many things config can do, here we set the backround color to teal removing the need of a canvas
root.config(bg = 'teal')
root.title('Weight Converter')
# We can also set the color of the lables using the bg option
labelText = tk.Label(root, text = "Weight Converter", bg = 'teal')
# We use pack to 'place' the widget so it shows up
labelText.pack()
# Now that we are not using the canvas we can pack the Entry widget
entry = tk.Entry(root)
entry.pack()
# Creating and placing the answer label
labelAnswer = tk.Label(root)
labelAnswer.pack()
# Our buttons that will call our conversion functions
b1 = tk.Button(root, text="to kg", command = to_kg)
b1.pack(side = 'bottom')
b2 = tk.Button(root, text='to pounds', command = to_pounds)
b2.pack(side = 'bottom')
root.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/370471.html
上一篇:全域前綴未設定變數
