有没有办法扩大python中的GUI框?

时间:2019-05-05 11:40:26

标签: python python-3.x tkinter

我正在尝试制作一个简单的句子生成器。该代码有效,但是我只想知道是否有任何方法可以扩展GUI输入框?

它是这样的:

enter image description here

任何帮助将不胜感激。

import tkinter as tk
from tkinter import Entry
import random
window = tk.Tk()

def movingVerb():
    verbs = ["goes to", "walks through", "runs through"]
    moveVerb = random.choice(verbs)
    return moveVerb
def anObject():
    anObject = objectEntry.get()
def Generate():
    UserName = nameEntry.get()
    moveVerb = movingVerb()
    place = placeEntry.get()
    noun = objectEntry.get()
    sentence = UserName + " " + moveVerb + " a " + place + " and finds a " + noun + " ." 
    result.delete(0, tk.END)
    result.insert(0, sentence)

UserNameLabel = tk.Label(window, text="Enter a name: ")
nameEntry = tk.Entry(window)
anObjectLabel = tk.Label(window,text="Enter an object: ")
objectEntry = tk.Entry(window)
placeLabel = tk.Label(window, text="Enter a place: ")
placeEntry = tk.Entry(window)
button = tk.Button(window, text="Generate story", command=Generate)
result = tk.Entry(window)

UserNameLabel.pack()
nameEntry.pack()
anObjectLabel.pack()
objectEntry.pack()
placeLabel.pack()
placeEntry.pack()
button.pack()
result.pack()
window.mainloop()

2 个答案:

答案 0 :(得分:1)

如果要在调整窗口大小时扩展小部件,则可以以不同组合使用expand中的fillpack()。一切取决于要扩展的元素以及向哪个方向扩展。

.pack(fill='x')
.pack(fill='y')
.pack(fill='both')
.pack(expand=True, fill='x')
.pack(expand=True, fill='y')
.pack(expand=True, fill='both')

enter image description here


如果要调整窗口大小以查看Entry中的所有新文本,则可以使用widget.configure(width=...)。条目使用字符数作为宽度。

您可以使用句子的长度更改宽度

result.configure(width=len(sentence))

或保持宽度至少20个字符

length = max(20, len(sentence))
result.configure(width=length)

完整代码

import tkinter as tk
import random

# --- functions ---

verbs = ["goes to", "walks through", "runs through"]

def generate():
    user_name = name_entry.get()
    move_verb = random.choice(verbs)
    place = place_entry.get()
    noun = object_entry.get()
    sentence = '{} {} a {} and finds a {}.'.format(user_name, move_verb, place, noun)
    result.delete(0, 'end')
    result.insert(0, sentence)
    length = max(20, len(sentence))
    result.configure(width=length)

# --- main ---

window = tk.Tk()

user_name_label = tk.Label(window, text="Enter a name: ")
name_entry = tk.Entry(window)
object_label = tk.Label(window,text="Enter an object: ")
object_entry = tk.Entry(window)
place_label = tk.Label(window, text="Enter a place: ")
place_entry = tk.Entry(window)
button = tk.Button(window, text="Generate story", command=generate)
result = tk.Entry(window)

user_name_label.pack(expand=True, fill='both')
name_entry.pack(fill='both')
object_label.pack(expand=True, fill='both')
object_entry.pack(fill='both')
place_label.pack(expand=True, fill='both')
place_entry.pack(fill='both')
button.pack(expand=True, fill='both')
result.pack(fill='both')

window.mainloop()

答案 1 :(得分:-1)

使用place而不是pack,您可以在此处执行此方法。

 placeLabel.place(relwidth=0.25, relheight=0.90)