我正在尝试创建一个窗口以显示数据框。但是,数据框太大,因此我想添加滚动条以能够查看数据。问题是滚动条出现但不起作用。我已经尝试了几种在这里找到的解决方案,但这些解决方案似乎都不适合我。
这是我的代码:
import tkinter as tk
root = tk.Tk()
#create frame
frame = tk.Frame(root)
frame.grid(sticky = 'news')
frame.grid_propagate(False)
#create Canvas
canvas = tk.Canvas(frame, bg = 'white')
canvas.grid(row = 0, column = 0)
#scrollbars
yscrollbar = tk.Scrollbar(frame, orient = tk.VERTICAL, command = canvas.yview)
yscrollbar.grid(row = 0, column = 1, sticky = tk.NS)
canvas.configure(yscrollcommand=yscrollbar.set)
xscrollbar = tk.Scrollbar(frame, orient = tk.HORIZONTAL, command = canvas.xview)
xscrollbar.grid(row = 1, column = 0, sticky = tk.EW)
canvas.configure(xscrollcommand=xscrollbar.set)
#new frame to contain text
frame_text = tk.Frame(canvas)
canvas.create_window((0, 0), window=frame_text, anchor='nw')
#insert dataframe
values = [['Abbreviation', 'UNIPROT Code', 'Full Name', 'Sample Type', 'Sample', 'Patients AGE±SD', 'Condition', 'Recurrence', 'Surgery', 'Patients Comorbidities', 'Patients (n)', 'Controls AGE±SD'],['MYL4', 'P12829', 'Myosin light chain 4', 'tissue', 'Left atrial appendages', '68.2±2.9', 'permanent', 'n', 'mitral valve surgery', 'MR (11)', '11.0', '58,8 ± 4,3'], ['AHSG', 'P02765', 'alpha2-HS glycoprotein', 'tissue', 'Right atrial appendages', '72±10', 'permanent (5), persistent (2), paroxysmal (1)', 'n', 'CABG or valve surgery', 'Hypertension (6), CAD (4)', '8.0', '65±12']]
widgets = []
for row in range(len(values)):
current_row = []
for column in range(len(values[0])):
label = tk.Label(frame_text, text=values[row][column],borderwidth=0, width=len(str(values[row][column])))
label.grid(row=row, column=column, sticky="nsew", padx=1, pady=1)
current_row.append(label)
widgets.append(current_row)
for column in range(len(values[0])):
frame_text.grid_columnconfigure(column, weight=1)
#Resize the canvas frame
frame.config(width = 1000 + yscrollbar.winfo_width(),height=1000+
xscrollbar.winfo_width())
canvas.config(scrollregion=canvas.bbox("all"))
此外,如何将画布大小设置为与窗口相同? 因为我现在得到的是: picture
答案 0 :(得分:1)
已解决
我意识到它不起作用的原因是,scrollabe区域比画布小。所以我改变了:
frame.config(width = 1000 + yscrollbar.winfo_width(),height=1000 + xscrollbar.winfo_width())
canvas.config(scrollregion=canvas.bbox("all"))
收件人:
frame.config(width = root.winfo_width(),height=root.winfo_height())
canvas.config(width = root.winfo_width()-yscrollbar.winfo_reqwidth()-10,height=root.winfo_height()-xscrollbar.winfo_reqheight()-10,scrollregion=(0,0,frame_text.winfo_reqwidth(),frame_text.winfo_reqheight()))
答案 1 :(得分:0)
我总是通过配置滚动条而不是画布来分配命令。 尝试替换行:
canvas.configure...
使用:
yscrollbar.config(command=canvas.yview)