Программа в настоящее время выглядит так:

Главное, что меня смущает почему карточки в рамке прокрутки внутри Canvas вызывают (возможно) растягивание видимой части кадра до концов экрана по желанию, но нет в результате чего весь ансамбль растягивается настолько высоко, что становится виден текст карты. Меня также сбивает с толку, почему между Labelframes и границами, на которых они предположительно упакованы, существует зазор (например, сбивает с толку зеленая линия под областью руки), но я не знаю, связана ли эта проблема с этим или нет.
Мой код становится все более запутанным, поскольку я пробовал различные методы из онлайн-руководств, чтобы исправить его, за что прошу прощения. Вот это сейчас:
Код: Выделить всё
from tkinter import *
from PIL import Image, ImageTk
from pathlib import Path
filedirectory = Path.cwd() #sets filedirectory to the current program's location
##Image handling
def ResizeImage(image,new_size=(300,500)):
tempImage=Image.open(image)
card=tempImage.resize(new_size) #Don't re-use variable for somereason, and do in extra lines? Test later.
return card #should probably do PhotoImage conversion here
##Window Management
root=Tk() #create a window
root.title("Frederick's Custom Dominion Game") #set the title of the window, which is displayed on window bar among other places.
icon = filedirectory.joinpath('img/icon.ico') #uses relative pathing to get the icon file
root.iconbitmap(icon) #sets the icon to the desired image I made
root.geometry("1800x1000") #set window size
root.configure(background="green") #like windows solitaire
frame = Frame(root,bg="green") #Creates a frame, which is a graphic that's generally designed to be identical to the background of the window and the same size as it for some reason.
frame.pack(side=BOTTOM, fill=BOTH,expand=1)
midframe=Frame(frame,bg="green") #use so we can pack the other way with the play and discard
player_hand=LabelFrame(frame,text='Hand',height=520,width=1520) #set up three labelFrames (which just draw a square and put a text label in the corner, but look nice)
play_area=LabelFrame(midframe,text='Play',height=520,width=1520) #height and width don't do anything without pack_propagate(0), but that's okay because we shouldn't be using them
discard=LabelFrame(midframe,text='discard',height=520,width=320)
player_hand.pack(side=BOTTOM,fill=X,expand=1) #This should be putting the hand across the entire bottom of the screen, but it's not
player_hand.update() #didn't work, didn't hurt
midframe.pack(side=BOTTOM,fill=BOTH,expand=1)
play_area.pack(side=LEFT,fill=X,expand=1)
discard.pack(side=RIGHT,expand=1)
scroll_bar = Scrollbar(player_hand,orient=HORIZONTAL) #place next to, not in, canvas. Linking is via configure *on both*
scroll_field=Canvas(player_hand,xscrollcommand=scroll_bar.set,highlightthickness=0)
scroll_field.config(scrollregion=scroll_field.bbox('all')) #bbox=bounding box, target self not inset Frame
scroll_bar.configure(orient=HORIZONTAL, command=scroll_field.xview) #target Canvas, not Frame
inside_frame=Frame(scroll_field, bg='blue') #this should grow to fit its contents, but it doesn't. Can't pack it, because that breaks scrolling.
###scroll code?
def updateScrollRegion():
scroll_field.update_idletasks()
scroll_field.config(scrollregion=scroll_field.bbox('all'))
root.update()
scroll_bar.pack( side = BOTTOM, fill = X,expand=1 )
scroll_field.create_window(0, 0, window=inside_frame, anchor=NW)
scroll_field.pack(fill=BOTH,side=LEFT,expand=TRUE) #Fill set to BOTH but still not growing vertically
root.after(1000,updateScrollRegion)
###
#deck logic
FuckGarbageCollection=[] #Why the heck are graphics garbage collected while still used in a Label?
flist = []
for f in Path(filedirectory.joinpath('img/Cards')).iterdir():
if f.is_file():
print(f)
flist.append(f)
class Card:
def __init__(self,file):
self.image=file
print(file)
FuckGarbageCollection.append(ImageTk.PhotoImage(ResizeImage(file))) #should move image processing from here to top of file
self.label=Label(inside_frame,image=FuckGarbageCollection[-1])
print("image complete")
AllCards=[]
for i in flist:
AllCards.append(Card(i))
for i in AllCards[:15]:
i.label.pack(side=LEFT,expand=1,fill=Y) #Does put cards in the box. Doesn't make the box fit.
root.update()
scroll_field.configure(scrollregion = scroll_field.bbox("all"))
updateScrollRegion()
def logic():
root.update()
player_hand.update()
scroll_field.update()
inside_frame.update()
updateScrollRegion()
root.after(1000,logic)
for i in inside_frame.children.values(): #no dice
i.update()
root.after(1000,logic)
root.mainloop()# spin forever?
Я пробовал использовать update() по-разному: либо до root.mainloop(), либо внутри него через after(). Я пробовал явно указывать разные вещи, чтобы заполнить пространство в разных направлениях или ОБА. Я попытался явно заставить Labelframes иметь правильные размеры, отключив распространение пакетов, что работает в том смысле, что он меняет их размеры, чтобы заполнить все, что я хочу, но их содержимое (например, изображения карточек и полоса прокрутки) все еще находится в странных местах и с изображения карточек обрезаны, и отображается дополнительный серый фон. Форсирование размеров также кажется плохой практикой для изучения, поэтому я бы предпочел избегать этого, хотя я мог бы временно заставить все работать нормально на моем компьютере/мониторе исключительно через Place() (или, может быть, просто отключив распространение , но в этот момент я бы просто использовал Place()).
Я пробовал читать некоторые файлы tkinter на github, но это в основном выходит за рамки моего уровня навыков, поэтому я почти уверен, что здесь нет очевидного ответа/синтаксической ошибки/отсутствующего аргумента, но я не удивлюсь, если узнаю обратное.
Я ожидал именно этого. что виджеты расширяются в соответствии со своим содержимым, поэтому все карточки должны отображаться в пределах размера экрана/окна и координат.
Подробнее здесь: https://stackoverflow.com/questions/784 ... in-tkinter