Внутренний фрейм Tkinter не обновляется при смене вкладкиPython

Программы на Python
Ответить Пред. темаСлед. тема
Гость
 Внутренний фрейм Tkinter не обновляется при смене вкладки

Сообщение Гость »


Я пытаюсь использовать to create an app that can read and edit values using input fields and then parse it in a later step.
I'm using the to display different items.
When I change tabs, the content inside the tab is not displayed until I move the mouse out of the tab button. Я пытаюсь использовать

Код: Выделить всё

update_idletasks
to force an update and binded it to

Код: Выделить всё

tabchange
.
I was previously using

Код: Выделить всё

ctk.CTkTabview
as the parent class, but I had some troubles with limited customizability, so I switched to

Код: Выделить всё

ttk.notebook
.
when i was using ctk.CTkTabview i bound update_idletasks to segmented callback button and it seemed to work as it should.

Код: Выделить всё

# Old code for ctk.CTkTabview
def _segmented_button_callback(self, selected_name):
super()._segmented_button_callback(selected_name)
self.myRefresh()

def myRefresh(self, event = None):
print("myRefresh")
self.tab_frame.update_idletasks()
My new code triggers the

Код: Выделить всё

update_idletasks()
binded to

Код: Выделить всё

NotebookTabChanged
, but the frame inside is still blank until I move my mouse out of the button.
Изображение

Код: Выделить всё

import tkinter as tk
from tkinter import ttk
import customtkinter as ctk

class BaseNotebook(ttk.Notebook):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

class MyTabViewEq(BaseNotebook):
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs)
self.tab_contents = {}  # To track content of each tab
self.bind("", self.fresh)

def add_tab_with_content(self, tab_name, fields_and_values):
# Check if tab already exists
if tab_name in self.tab_contents:
return  # Optionally, focus the existing tab instead of returning

new_tab_frame = tk.Frame(self)
self.add(new_tab_frame, text=tab_name)
self.tab_contents[tab_name] = {"frame": new_tab_frame, "fields_and_values": fields_and_values, "entry_widgets": {}}
tab_dict = {"test": "test", "test2": "test2"}
# Populate the tab
self.populate_tab(new_tab_frame, tab_name, tab_dict, fields_and_values)

# Focus the newly created tab
self.select(new_tab_frame)

def populate_tab(self, tab_frame, tab_name, tab_dict, fields_and_values):

scrollable_frame = ctk.CTkScrollableFrame(tab_frame)  # Assuming you have a scrolling mechanism
scrollable_frame.pack(fill='both', expand=True, padx=10, pady=10)
# self.tab_contents[tab_name]["scrollable_frame"] = scrollable_frame

self.tab_contents[tab_name]["scrollable_frame"] = scrollable_frame

dict_frame = tk.Frame(scrollable_frame)  # Specify corner radius for rounded corners if desired
dict_frame.pack(fill='x', padx=10, pady=(10, 0), expand=True)

button = ttk.Button(dict_frame, text="Save Button", command=self.buttonclick)
button.pack(side='left', padx=10, pady=10)

# tab top info
for key, value in tab_dict.items():
label = tk.Label(scrollable_frame, text=f"{key}:  {value}")
label.pack(padx=10, Pady=5,nchor='w')

input_fields_frame = tk.Frame(scrollable_frame)
input_fields_frame.pack (fill='both',expand=True,padx=10,pady=10)
self.populate_input_fields(tab_name, input_fields_frame, field_and_values)

def Fresh(self, event=None) :
current_tab = self.nametowidget(self.select())
if hasattr(current_tab, 'update_idletasks'):
print(current_tab)
current_tab.update_idletasks()
else:
print("Нет update_idletasks")

def buttonclick(self):
print("кнопка нажата")

def populate_input_fields (self, имя_вкладки, рамка, поля_и_значения):
enter_widgets = self.tab_contents[tab_name]["entry_widgets"]
для строки (имя, значение) в перечислении(fields_and_values.items()):< br /> label = tk.Label(frame, text=f"{name}:")
label.grid(row=row, Column=0, Pady=10, Sticky="w")
запись = tk.Entry(frame)
enter.grid(row=row,column=1,pady=10,sticky="ew",padx=(5, 20))
frame.grid_columnconfigure (1, вес=1)
вход_виджеты[имя] = запись
запись.вставка(0, значение)
def main():
root = tk.Tk()< br /> root.geometry("600x400")

# Примеры полей и значений
field_and_values ​​= {
'Field1': 'Value1',
'Field2' : 'Значение2',
'Поле3': 'Значение3',

блокнот = MyTabViewEq(root)
Notebook.pack(expand=True, fill= 'both')

# Добавление образца вкладки
Notebook.add_tab_with_content("Tab 1", field_and_values)
Notebook.add_tab_with_content("Tab 2", Fields_and_values)

root.mainloop()

if __name__ == "__main__":
main()


Источник: https://stackoverflow.com/questions/781 ... tab-change
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Проверка теряется при смене вкладки [дубликат]
    Anonymous » » в форуме C#
    0 Ответы
    6 Просмотры
    Последнее сообщение Anonymous
  • Использует ли hibernate внутренний jdbc или внутренний JTA, или его можно настроить?
    Anonymous » » в форуме JAVA
    0 Ответы
    48 Просмотры
    Последнее сообщение Anonymous
  • Когда я вызываю поток(), где находится внутренний итератор или внутренний сплиттератор?
    Anonymous » » в форуме JAVA
    0 Ответы
    37 Просмотры
    Последнее сообщение Anonymous
  • Когда я вызываю поток(), где находится внутренний итератор или внутренний сплиттератор?
    Anonymous » » в форуме JAVA
    0 Ответы
    39 Просмотры
    Последнее сообщение Anonymous
  • Вкладки Bootstrap – изменение вкладки при нажатии кнопки «Назад»
    Anonymous » » в форуме Jquery
    0 Ответы
    180 Просмотры
    Последнее сообщение Anonymous

Вернуться в «Python»