我正在使用 Windows 10 和 Anaconda Jupyter Python 3.9.12。我正在嘗試使用一個按鈕構建一個 GUI,每次單擊該按鈕時,該按鈕都會從 Excel 檔案中隨機選擇一個問題。它作業正常。但是當問題太長時,它就像所附的螢屏截圖一樣被切斷。我希望斷線,這樣我就可以閱讀整個問題并回答它。我嘗試了 wraplength 引數,但它沒有給我預期的輸出。
這是代碼:
import tkinter as tk
from tkinter import *
from tkinter import WORD
import pandas as pd
import random
from textwrap import wrap
window = Tk()
window.title("Welcome to your Q App")
window.geometry('900x500')
window.config(bg="#F39C12")
window.resizable(width=False,height=False)
lbl = Label(window, text="Q")
df = "Mittagessen: Sie ordern ein Steak, englisch. Der Kellner bringt es durchgebraten. Was tun Sie?"
def random():
global l2
global l1
df1 = df
Q = df1
l2.config(text = Q)
btn = Button(window, text="Pick up a question", bg="blue", fg="black", command= random)
btn.grid(column=1, row=5)
l1 = tk.Label(window, text="Please answer",font=("Arial",15),bg="Black",fg="White")
l2 = tk.Label(window, bg="#F73C12",font=("Arial",15), text= "", width=100, justify=CENTER, compound=tk.CENTER)
l2.bind("<Configure>", random)
l2.grid(column=1, row=7)
l1.grid(column=1, row=4)
window.mainloop()
編輯:我在代碼中放置了直接文本 - df - 而不是 Excel 檔案路徑。

uj5u.com熱心網友回復:
我不知道這是否可以解決它,但我發現很少有元素會造成問題。
您使用width=100which 可以創建比視窗更長的標簽,但resizable(width=False,height=False)不允許調整其大小以顯示完整標簽。
但我認為主要問題是因為您從中獲取行DataFrame并將其直接發送到小部件,因此DataFrame將其轉換為字串添加空格并...用于在文本控制臺中創建漂亮的表格。但是這張表在 GUI 中不一定要好看。您應該只從行中獲取問題或自行格式化行中的所有資料。
包含一些資料的最小作業代碼,DataFrame我df.sample().values[0][1]用來只獲取沒有header行號的問題。或者df.sample().values[0]獲取行并將其手動轉換為字串。
后來我可以使用wrap()或自己的方法拆分為多行。
我使用pack(fill="x")而不是grid()因為它更容易調整到全視窗。
import tkinter as tk
import random
import textwrap
import pandas as pd
# --- functions ---
def get_random():
#Q = df[['type', 'question']].sample().values[0][1]
#print('Q:', Q)
row = df[['type', 'question']].sample().values[0]
print('row:', row)
Q = '\n'.join(row)
print('Q:', Q)
# - wrap on length -
#Q = textwrap.wrap(Q, width=70)
# - wrap on . and : -
Q = Q.replace('. ', '.\n')#.replace(': ', ':\n')
print('Q:', Q)
print('---')
question.config(text=Q)
# --- main ---
df = pd.DataFrame({
'type': [
'Mittagessen:',
'Short:',
'Frage:',
],
'question': [
'Sie ordern ein Steak, englisch. Der Kellner bringt es durchgebraten. Was tun Sie?',
'Sentence 1. Sentence 2. Question?',
'Wie wichtig ist Ihnen unternehmerisches Denken'
],
'answer': [
'A',
'B',
'C',
]
})
# - gui -
window = tk.Tk()
window.title("Welcome to your Q App")
window.geometry('900x500')
window.config(bg="#F39C12")
window.resizable(width=False, height=False)
btn = tk.Button(window, text="Pick up a question", bg="blue", fg="black", command=get_random)
btn.pack()
label = tk.Label(window, text="Please answer", font=("Arial",15), bg="black", fg="white")
label.pack()
question = tk.Label(window, bg="#F73C12", font=("Arial",15))
question.pack(fill='x')#, padx=25)
get_random()
window.mainloop()

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/497227.html
