updating screen after poping to it #5402
-
I have screens:
KeysView(1st ) and RenameKeyView(2nd). When im pushing to 2nd and renaming key, i call a pop_screen that returns me to the 1st screen, and the table with contains the key, that i just update. class KeysView(BaseScreen):
def __init__(self, mode=None):
super().__init__()
self.mode = mode
self.rename_input = None # Инициализируем переменную для хранения ссылки на Input
def compose(self):
yield Static("Ключи:")
self.table = DataTable()
self.table.add_column("Device ID")
self.table.add_column("Name")
self.table.add_column("Outline Key")
self.load_devices()
yield self.table
yield Button("Создать новый ключ", name="add_key", variant="success")
yield Button("Переименовать выбранный ключ", name="rename", variant="primary")
yield Button.error("Удалить выбранный ключ", name="del")
yield Button("Назад", name="back")
def load_devices(self):
data = load_data()
devices = []
for u in data['users']:
if u['user_id'] == 'admin':
devices = u.get('devices', [])
break
self.table.clear() # Очистка таблицы перед загрузкой новых данных
for d in devices:
self.table.add_row(d['device_id'], d['device_name'], d['outline_key'])
def on_button_pressed(self, event):
if event.button.name == "back":
self.app.pop_screen()
elif event.button.name == "del":
self.delete_selected_device()
self.refresh_keys()
elif event.button.name == "rename":
self.app.push_screen(RenameKeyView())
self.refresh_keys()
elif event.button.name == "add_key":
from ui.add_key_view import AddKeyView
self.app.push_screen(AddKeyView())
self.refresh_keys()
class RenameKeyView(BaseScreen):
def __init__(self, mode=None):
super().__init__()
self.mode = mode
self.rename_input = None
def compose(self):
yield Static("Ключи:")
self.table = DataTable()
self.table.add_column("Device ID")
self.table.add_column("Name")
self.table.add_column("Outline Key")
self.load_devices()
yield self.table
self.rename_input = Input(placeholder="Новое имя", name="rename_input")
yield self.rename_input
yield Button("Переименовать выбранный ключ", name="rename")
yield Button("Назад", name="back")
def rename_selected_device(self):
selected = self.table.cursor_row
new_name = self.rename_input.value.strip()
if new_name:
row_data = self.table.get_row_at(selected)
device_id = row_data[0]
rename_outline_access_key(device_id, new_name)
self.app.push_screen(MessageView("Готово", "Ключ переименован."))
else:
self.app.push_screen(MessageView("Ошибка", "Новое имя не может быть пустым."))
def on_button_pressed(self, event):
if event.button.name == "rename":
self.app.push_screen(RenameKeyView())
self.rename_selected_device()
if event.button.name == "back":
self.app.pop_screen()
class BaseScreen(Screen):
def refresh_keys(self, mode = None):
keys = get_outline_access_keys()
if keys is None:
self.app.push_screen(MessageView("Ошибка", "Не удалось обновить ключи. Проверьте настройки."))
return
self.update_users_yaml(keys)
if mode == "refresh":
self.app.push_screen(MessageView("Успех", "Ключи обновлены."))
def update_users_yaml(self, keys):
data = load_data()
user = next((u for u in data['users'] if u['user_id'] == 'admin'), None)
if not user:
user = {'user_id': 'admin', 'name': 'admin_user', 'devices': []}
data['users'].append(user)
user['devices'].clear()
for k in keys:
device = {
'device_id': k.key_id,
'device_name': k.name,
'outline_key': k.access_url
}
user['devices'].append(device)
save_data(data) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
the only way i can see now - is to delete KeysView.py screen after pushing to RenameKeyView.py screen, and to push to KeysView.py again, so it will call load_table with the correct data |
Beta Was this translation helpful? Give feedback.
-
I found a event.Show class, but idk why it doesn't work # ui/keys_view.py
from textual import work
from textual.events import Show
from textual.widgets import Static, Button, DataTable
from managers.data_manager import load_data
from managers.device_manager import delete_device
from ui.base_screen import BaseScreen
from ui.message_view import MessageView
from ui.rename_key_view import RenameKeyView
class KeysView(BaseScreen):
def __init__(self, mode=None):
super().__init__()
self.table = None
self.mode = mode
self.rename_input = None # Инициализируем переменную для хранения ссылки на Input
def compose(self):
yield Static("Ключи:")
self.table = DataTable()
self.table.add_column("Device ID")
self.table.add_column("Name")
self.table.add_column("Outline Key")
self.refresh_keys()
self.load_devices()
yield self.table
yield Button("Создать новый ключ", name="add_key", variant="success")
yield Button("Переименовать выбранный ключ", name="rename", variant="primary")
yield Button.error("Удалить выбранный ключ", name="del")
yield Button("Назад", name="back")
def load_devices(self):
data = load_data()
devices = []
for u in data['users']:
if u['user_id'] == 'admin':
devices = u.get('devices', [])
break
self.table.clear() # Очистка таблицы перед загрузкой новых данных
for d in devices:
self.table.add_row(d['device_id'], d['device_name'], d['outline_key'])
def on_button_pressed(self, event):
if event.button.name == "back":
self.app.pop_screen()
elif event.button.name == "del":
self.delete_selected_device()
#self.refresh_keys()
elif event.button.name == "rename":
self.app.push_screen(RenameKeyView())
#self.refresh_keys()
elif event.button.name == "add_key":
from ui.add_key_view import AddKeyView
self.app.push_screen(AddKeyView())
#self.recompose()
#self.refresh_keys()
async def on_show(self, event: Show):
self.refresh_keys()
self.load_devices()
def delete_selected_device(self):
selected = self.table.cursor_row
if selected is not None:
row_data = self.table.get_row_at(selected)
device_id = row_data[0]
delete_device("admin", device_id)
self.table.clear()
#self.refresh_keys()
#self.load_devices()
self.app.push_screen(MessageView("Готово", f"Ключ удалён. ID: {device_id}")) |
Beta Was this translation helpful? Give feedback.
It's an event. It works like all other events. Just like on_show, on_button_pressed. You implement
on_screen_resume
, which Textual calls when the screen is active again.