Уведомления

Группа в Telegram: @pythonsu
  • Начало
  • » GUI
  • » сохранить введённые в окно tkinter значения [RSS Feed]

#1 Фев. 11, 2022 19:10:38

Ynejus
Зарегистрирован: 2021-12-25
Сообщения: 12
Репутация: +  0  -
Профиль   Отправить e-mail  

сохранить введённые в окно tkinter значения

Пытаюсь добавить функцию, которая бы считывала вводимые в поля значения для их дальнейшего использования.
Для хранения используемых значений хочу использовать словарь.

 import tkinter
from tkinter.ttk import Entry, Combobox, Checkbutton
variables_list = ['list','entry','check'] # это те значения, что различаются 
constants = {
'names':['alex','billy'],
'color': {'red':12,
          'green':15,
          'yellow':19,
          'brown':18,
          'grey':6},
}
class MainWindow():
    
    def __init__(self):  #создаю окно
        self.root = tkinter.Tk()
    def label_const(self):   #рисую кнопки и пишу названия строчек
        for i in variables_list: tkinter.Label(self.root,text = i).place(y = 20 + variables_list.index(i)*20)
        tkinter.Button(self.root,text = 'Set',command = self.label_var).place(y=80)
        tkinter.Button(self.root,text = 'Get',command = self.label_get).place(y=105)
        tkinter.Button(self.root,text = 'GO!',command = self.print).place(y=130)
    def print(self):
        print(self.variables)
    def label_var(self): 
        self.variables = dict.fromkeys(constants['names'],dict.fromkeys(variables_list,[])) # создаю словарь, в который буду добавлять значения
        for i in range(len(constants['names'])):
            x = 50+60*i  #отступ от края
            tkinter.Label(text=constants['names'][i]).place(x=x,y=0) # пишу имена столбцов
## вот тут я лажаю :-(
            self.var = Combobox(values=tuple(constants['color'].keys()),width = 5) 
            self.var.place(x=x,y=20) #выпадающий список
            self.variables[constants['names'][i]]['list'].append(self.var) 
#от этой строки ожидалось, что в словарь 'variables' в список ['list'] по ключу constants['names'][i] будет добавлен объект <tkinter.ttk.Combobox object .!combobox>
#в дальнейшем, после выбора нужного значения (ввода текста или установки галочки) предполагалось записать это значение в другой словарь или просто перезаписать его на string.
            self.var = tkinter.Entry(width = 5)
            self.var.place(x=x,y=40) #ввод вручную
            self.variables[constants['names'][i]]['entry'].append(self.var)
            self.var = Checkbutton(width = 5)
            self.var.place(x=x,y=60) # отметка
            self.variables[constants['names'][i]]['check'].append(self.var)
        print(self.variables) # нужно для проверки. Ожидался словарь 2х3х1, но вывод удручающ.
    def label_get(self):
        print('Получение переменных')
        self.variables_cur = dict.fromkeys(variables_list,[])
        for i in range(len(constants['names'])):
            for j in range(len(variables_list)):
                print('ключ словаря переменной ',list(self.variables_cur.keys())[j])
                print('тип переменной ',type(self.variables[str(list(self.variables.keys())[j])][i]))
                print('значение переменной ',self.variables[str(list(self.variables.keys())[j])][i])
                #self.variables_cur[str(list(self.variables_cur.keys())[j])].append(self.variables[str(list(self.variables.keys())[j])][i].get()) 
                #self.variables_cur[str(list(self.variables_cur.keys())[j])][i] = self.variables[str(list(self.variables.keys())[j])][i].get() 
                print('тип переменной ',type(self.variables_cur[str(list(self.variables_cur.keys())[j])][i]))
                print('значение переменной ',self.variables_cur[str(list(self.variables_cur.keys())[j])][i])
    def run(self):
        self.label_const()
        self.label_var()
        self.root.mainloop()
window = MainWindow()
window.run()
Пожалуйста, подскажите, что делать, или хотя бы в какую сторону нужно читать?

Офлайн

#2 Фев. 12, 2022 06:51:49

AD0DE412
Зарегистрирован: 2019-05-12
Сообщения: 1130
Репутация: +  44  -
Профиль   Отправить e-mail  

сохранить введённые в окно tkinter значения

это и я вот о чем …
опишите что должна делать программа
опишите как пытаетесь это сделать
опишите что не получается (+ вывод ошибок если есть)

итд а то чет не хочется по сломоному коду догадываться как он должен работать но не работает

зы то что вам кажется очевидным
не всегда кажется очевидным другим
и да
если вы здесь и просите помощь
то ваше чувство очиведности
очевидно ложное



1. пжлст, форматируйте код, это в панели создания сообщений, выделите код и нажмите что то вроде
2. чтобы вставить изображение залейте его куда нибудь (например), нажмите и вставьте ссылку на его url

есчщо

Отредактировано AD0DE412 (Фев. 12, 2022 06:54:53)

Офлайн

#3 Фев. 12, 2022 10:03:29

AD0DE412
Зарегистрирован: 2019-05-12
Сообщения: 1130
Репутация: +  44  -
Профиль   Отправить e-mail  

сохранить введённые в окно tkinter значения

вот пример вводите в текстовое поле строчку нажимаете add добавляете в комбо ну и тама еще del и print кроче там вроде ясно все
unknown.py

 #! /usr/bin/env python
#  -*- coding: utf-8 -*-
import sys
try:
    import Tkinter as tk
except ImportError:
    import tkinter as tk
try:
    import ttk
    py3 = False
except ImportError:
    import tkinter.ttk as ttk
    py3 = True
import unknown_support
def vp_start_gui():
    '''Starting point when module is the main routine.'''
    global val, w, root
    root = tk.Tk()
    unknown_support.set_Tk_var()
    top = Toplevel1 (root)
    unknown_support.init(root, top)
    root.mainloop()
w = None
def create_Toplevel1(rt, *args, **kwargs):
    '''Starting point when module is imported by another module.
       Correct form of call: 'create_Toplevel1(root, *args, **kwargs)' .'''
    global w, w_win, root
    #rt = root
    root = rt
    w = tk.Toplevel (root)
    unknown_support.set_Tk_var()
    top = Toplevel1 (w)
    unknown_support.init(w, top, *args, **kwargs)
    return (w, top)
def destroy_Toplevel1():
    global w
    w.destroy()
    w = None
class Toplevel1:
    def __init__(self, top=None):
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''
        _bgcolor = '#d9d9d9'  # X11 color: 'gray85'
        _fgcolor = '#000000'  # X11 color: 'black'
        _compcolor = '#d9d9d9' # X11 color: 'gray85'
        _ana1color = '#d9d9d9' # X11 color: 'gray85'
        _ana2color = '#ececec' # Closest X11 color: 'gray92'
        self.style = ttk.Style()
        if sys.platform == "win32":
            self.style.theme_use('winnative')
        self.style.configure('.',background=_bgcolor)
        self.style.configure('.',foreground=_fgcolor)
        self.style.configure('.',font="TkDefaultFont")
        self.style.map('.',background=
            [('selected', _compcolor), ('active',_ana2color)])
        top.geometry("222x135+503+286")
        top.minsize(116, 1)
        top.maxsize(1436, 874)
        top.resizable(1,  1)
        top.title("New Toplevel")
        top.configure(background="#d9d9d9")
        top.configure(highlightbackground="#d9d9d9")
        top.configure(highlightcolor="black")
        self.Text1 = tk.Text(top)
        self.Text1.place(relx=0.045, rely=0.37, relheight=0.259, relwidth=0.874)
        self.Text1.configure(background="white")
        self.Text1.configure(font="TkTextFont")
        self.Text1.configure(foreground="black")
        self.Text1.configure(highlightbackground="#d9d9d9")
        self.Text1.configure(highlightcolor="black")
        self.Text1.configure(insertbackground="black")
        self.Text1.configure(selectbackground="blue")
        self.Text1.configure(selectforeground="white")
        self.Text1.configure(wrap="word")
        self.Button1 = tk.Button(top)
        self.Button1.place(relx=0.09, rely=0.741, height=24, width=47)
        self.Button1.configure(activebackground="#ececec")
        self.Button1.configure(activeforeground="#000000")
        self.Button1.configure(background="#d9d9d9")
        self.Button1.configure(command=unknown_support.add_)
        self.Button1.configure(disabledforeground="#a3a3a3")
        self.Button1.configure(foreground="#000000")
        self.Button1.configure(highlightbackground="#d9d9d9")
        self.Button1.configure(highlightcolor="black")
        self.Button1.configure(pady="0")
        self.Button1.configure(text='''add''')
        self.Button2 = tk.Button(top)
        self.Button2.place(relx=0.405, rely=0.741, height=24, width=47)
        self.Button2.configure(activebackground="#ececec")
        self.Button2.configure(activeforeground="#000000")
        self.Button2.configure(background="#d9d9d9")
        self.Button2.configure(command=unknown_support.print_)
        self.Button2.configure(disabledforeground="#a3a3a3")
        self.Button2.configure(foreground="#000000")
        self.Button2.configure(highlightbackground="#d9d9d9")
        self.Button2.configure(highlightcolor="black")
        self.Button2.configure(pady="0")
        self.Button2.configure(text='''print''')
        self.TCombobox1 = ttk.Combobox(top)
        self.TCombobox1.set(0)
        self.TCombobox1.place(relx=0.045, rely=0.074, relheight=0.156
                , relwidth=0.869)
        self.value_list = ['']
        self.TCombobox1.configure(values=self.value_list)
        self.TCombobox1.configure(justify='right')
        self.TCombobox1.configure(textvariable=unknown_support.combobox)
        self.TCombobox1.configure(takefocus="")
        self.Button3 = tk.Button(top)
        self.Button3.place(relx=0.721, rely=0.741, height=24, width=47)
        self.Button3.configure(activebackground="#ececec")
        self.Button3.configure(activeforeground="#000000")
        self.Button3.configure(background="#d9d9d9")
        self.Button3.configure(command=unknown_support.del_)
        self.Button3.configure(disabledforeground="#a3a3a3")
        self.Button3.configure(foreground="#000000")
        self.Button3.configure(highlightbackground="#d9d9d9")
        self.Button3.configure(highlightcolor="black")
        self.Button3.configure(pady="0")
        self.Button3.configure(text='''del''')
if __name__ == '__main__':
    vp_start_gui()
unknown_support.py
 #! /usr/bin/env python
#  -*- coding: utf-8 -*-
import sys
try:
    import Tkinter as tk
except ImportError:
    import tkinter as tk
try:
    import ttk
    py3 = False
except ImportError:
    import tkinter.ttk as ttk
    py3 = True
def set_Tk_var():
    global combobox
    combobox = tk.StringVar()
def init(top, gui, *args, **kwargs):
    global w, top_level, root
    w = gui
    top_level = top
    root = top
def add_():
    global w, top_level, root
    txt = w.Text1.get('1.0', 'end')
    w.value_list.append(txt)
    w.TCombobox1['values'] = w.value_list
    w.Text1.delete('1.0', 'end')
    print('unknown_support.add_', txt)
    sys.stdout.flush()
def del_():
    if len(w.value_list) > 1:
        w.Text1.delete('1.0', 'end')
        txt = w.TCombobox1.get()
        w.value_list.pop(w.value_list.index(txt))
    else:
        w.Text1.delete('1.0', 'end')
        w.value_list = ['']
    w.TCombobox1['values'] = w.value_list
    w.TCombobox1.set(w.value_list[0])
    print('unknown_support.del_')
        
    sys.stdout.flush()
    
def print_():
    txt = w.TCombobox1.get()
    w.Text1.insert('1.0', txt)
    print('unknown_support.print_', txt)
    sys.stdout.flush()
def destroy_window():
    # Function which closes the window.
    global top_level
    top_level.destroy()
    top_level = None
if __name__ == '__main__':
    import unknown
    unknown.vp_start_gui()



1. пжлст, форматируйте код, это в панели создания сообщений, выделите код и нажмите что то вроде
2. чтобы вставить изображение залейте его куда нибудь (например), нажмите и вставьте ссылку на его url

есчщо

Офлайн

#4 Фев. 12, 2022 10:17:53

Ynejus
Зарегистрирован: 2021-12-25
Сообщения: 12
Репутация: +  0  -
Профиль   Отправить e-mail  

сохранить введённые в окно tkinter значения

AD0DE412
Программа должна рисовать окно,
 import tkinter
from tkinter.ttk import Entry, Combobox, Checkbutton
variables_list = ['list','entry','check']
constants = {
'names':['alex','billy'],
'color': {'red':12,
          'green':15,
          'yellow':19,
          'brown':18,
          'grey':6},
}
class MainWindow():
    
    def __init__(self):
        self.root = tkinter.Tk()
В котором есть несколько строк: выпадающий список, поле ввода, чекбокс и кнопок
     def label_const(self):
        for i in variables_list: tkinter.Label(self.root,text = i).place(y = 20 + variables_list.index(i)*20)
        tkinter.Button(self.root,text = 'Set',command = self.label_var).place(y=80)
        tkinter.Button(self.root,text = 'Get',command = self.label_get).place(y=105)
        tkinter.Button(self.root,text = 'GO!',command = self.print).place(y=130)
Строки разделены на несколько столбцов, названных alex, billy, charlie и так далее. Количество столбцов может быть различным и зависит от содержимого constants = {'names':….}

     def label_var(self):
        for i in range(len(constants['names'])):
            x = 50+60*i
            tkinter.Label(text=constants['names'][i]).place(x=x,y=0)

При запуске я ожидаю, что tkinter нарисует окно и элементы ввода
     def run(self):
        self.label_const()
        self.label_var()
        self.root.mainloop()
window = MainWindow()
window.run()

Для этого я создаю словарь, в котором хотел бы хранить вводимые значения
     def label_var(self):
        self.variables = dict.fromkeys(constants['names'],dict.fromkeys(variables_list,[]))
        print(self.variables)
        for i in range(len(constants['names'])):
            x = 50+60*i
            tkinter.Label(text=constants['names'][i]).place(x=x,y=0)
            self.var = Combobox(values=tuple(constants['color'].keys()),width = 5) 
            self.var.place(x=x,y=20) #выпадающий список
            self.variables[constants['names'][i]]['list'].append(self.var)
##            self.var = tkinter.Entry(width = 5)
##            self.var.place(x=x,y=40) #ввод вручную
##            self.variables[constants['names'][i]]['entry'].append(self.var)
##            self.var = Checkbutton(width = 5)
##            self.var.place(x=x,y=60) # отметка
##            self.variables[constants['names'][i]]['check'].append(self.var)
       print(self.variables)
часть строк закомментировано для краткости
Первый print(self.variables) выдаёт: {'alex': {'list': , ‘entry’: , ‘check’: }, ‘billy’: {'list': , ‘entry’: , ‘check’: }}
Дальше я ожидал, что первая итерация цикла напишет ‘alex’,
создаст атрибут метода
  self.var = Combobox(values=tuple(constants['color'].keys()),width = 5)
и добавит его в список
  self.variables[constants['names'][i]]['list'].append(self.var)
Поэтому я ожидал, что второй print(self.variables) выдаст что-то вроде
 {'alex': {'list': [<tkinter.ttk.Combobox object .!combobox>], 'entry': [], 'check': []},
'billy': {'list': [<tkinter.ttk.Combobox object .!combobox2>], 'entry': [], 'check': []}} 
, но получаю
  
{'alex': {'list': [<tkinter.ttk.Combobox object .!combobox>, <tkinter.ttk.Combobox object .!combobox2>],
 'entry': [<tkinter.ttk.Combobox object .!combobox>, <tkinter.ttk.Combobox object .!combobox2>], 
'check': [<tkinter.ttk.Combobox object .!combobox>, <tkinter.ttk.Combobox object .!combobox2>]}, 
'billy': {'list': [<tkinter.ttk.Combobox object .!combobox>, <tkinter.ttk.Combobox object .!combobox2>], 
'entry': [<tkinter.ttk.Combobox object .!combobox>, <tkinter.ttk.Combobox object .!combobox2>], 
'check': [<tkinter.ttk.Combobox object .!combobox>, <tkinter.ttk.Combobox object .!combobox2>]}}
Больше ошибок нет

Отредактировано Ynejus (Фев. 12, 2022 10:37:52)

Офлайн

#5 Фев. 12, 2022 10:39:47

AD0DE412
Зарегистрирован: 2019-05-12
Сообщения: 1130
Репутация: +  44  -
Профиль   Отправить e-mail  

сохранить введённые в окно tkinter значения

так оно и сохраняет объекты <tkinter.ttk.Combobox object .!combobox> ээ что не так?



1. пжлст, форматируйте код, это в панели создания сообщений, выделите код и нажмите что то вроде
2. чтобы вставить изображение залейте его куда нибудь (например), нажмите и вставьте ссылку на его url

есчщо

Отредактировано AD0DE412 (Фев. 12, 2022 10:41:12)

Офлайн

#6 Фев. 12, 2022 10:46:29

Ynejus
Зарегистрирован: 2021-12-25
Сообщения: 12
Репутация: +  0  -
Профиль   Отправить e-mail  

сохранить введённые в окно tkinter значения

Оно сохраняет, но я полагал, что будет сохранено только Combobox и только в списке list. А оно записывает и в entry, и в check.

Офлайн

#7 Фев. 12, 2022 21:48:22

AD0DE412
Зарегистрирован: 2019-05-12
Сообщения: 1130
Репутация: +  44  -
Профиль   Отправить e-mail  

сохранить введённые в окно tkinter значения

перепишите свой код как то так

 #! /usr/bin/env python
#  -*- coding: utf-8 -*-
import sys
import tkinter as tk
import tkinter.ttk as ttk
class Toplevel1():
    def __init__(self, top=None):
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''
        top.geometry("229x197+688+321")
        top.resizable(0, 0)
        top.title("New Toplevel")
        self.Label1 = tk.Label(top)
        self.Label1.place(relx=0.044, rely=0.152, height=21, width=34)
        self.Label1.configure(text='''list''')
        self.Label2 = tk.Label(top)
        self.Label2.place(relx=0.044, rely=0.305, height=21, width=34)
        self.Label2.configure(text='''entry''')
        self.Label3 = tk.Label(top)
        self.Label3.place(relx=0.044, rely=0.457, height=21, width=34)
        self.Label3.configure(text='''check''')
        self.Label4 = tk.Label(top)
        self.Label4.place(relx=0.262, rely=0.051, height=21, width=34)
        self.Label4.configure(text='''alex''')
        self.Label5 = tk.Label(top)
        self.Label5.place(relx=0.568, rely=0.051, height=21, width=34)
        self.Label5.configure(text='''billy''')
        self.TCombobox1 = ttk.Combobox(top)
        self.TCombobox1.place(
            relx=0.262, rely=0.152, relheight=0.107, relwidth=0.231
        )
        self.TCombobox1.configure(takefocus="")
        self.TCombobox2 = ttk.Combobox(top)
        self.TCombobox2.place(
            relx=0.568, rely=0.152, relheight=0.107, relwidth=0.231
        )
        self.TCombobox2.configure(takefocus="")
        self.TEntry1 = ttk.Entry(top)
        self.TEntry1.place(
            relx=0.262, rely=0.305, relheight=0.107, relwidth=0.201
        )
        self.TEntry2 = ttk.Entry(top)
        self.TEntry2.place(
            relx=0.568, rely=0.305, relheight=0.107, relwidth=0.201
        )
        self.check = tk.IntVar()
        self.Checkbutton1 = tk.Checkbutton(top)
        self.Checkbutton1.place(
            relx=0.262, rely=0.457, relheight=0.127, relwidth=0.266
        )
        self.Checkbutton1.configure(anchor='w')
        self.Checkbutton1.configure(justify='left')
        self.Checkbutton1.configure(variable=self.check)
        
        self.Checkbutton2 = tk.Checkbutton(top)
        self.Checkbutton2.place(
            relx=0.568, rely=0.457, relheight=0.127, relwidth=0.266
        )
        self.Checkbutton2.configure(anchor='w')
        self.Checkbutton2.configure(justify='left')
        self.Button1 = tk.Button(top)
        self.Button1.place(
            relx=0.044, rely=0.609, height=24, width=47
        )
        self.Button1.configure(command=self.set_)
        self.Button1.configure(pady="0")
        self.Button1.configure(text='''set''')
        self.Button2 = tk.Button(top)
        self.Button2.place(
            relx=0.306, rely=0.609, height=24, width=47
        )
        self.Button2.configure(command=self.get_)
        self.Button2.configure(pady="0")
        self.Button2.configure(text='''get''')
        self.Button3 = tk.Button(top)
        self.Button3.place(
            relx=0.568, rely=0.609, height=24, width=47
        )
        self.Button3.configure(command=self.go_)
        self.Button3.configure(pady="0")
        self.Button3.configure(text='''go''')
    def set_(self):
        print('set_')
        what_there = f'{self.check.get()}'
        
        print(what_there)
        pass
    
    def get_(self):
        print('get_')
        pass
    
    def go_(self):
        print('go_')
        pass
if __name__ == '__main__':
    root = tk.Tk()
    w = Toplevel1(root)
    root.mainloop()
а то очень запутано
и чего совсем не понимаю зачем вы сохраняете объекты берите нужные значения а объекты остаются сборщику мусора



1. пжлст, форматируйте код, это в панели создания сообщений, выделите код и нажмите что то вроде
2. чтобы вставить изображение залейте его куда нибудь (например), нажмите и вставьте ссылку на его url

есчщо

Отредактировано AD0DE412 (Фев. 12, 2022 21:56:26)

Офлайн

  • Начало
  • » GUI
  • » сохранить введённые в окно tkinter значения[RSS Feed]

Board footer

Модераторировать

Powered by DjangoBB

Lo-Fi Version