Почему свойства позиции (pos и pos_hint) не влияют на размещение виджета в моем приложении Kivy?Python

Программы на Python
Ответить
Anonymous
 Почему свойства позиции (pos и pos_hint) не влияют на размещение виджета в моем приложении Kivy?

Сообщение Anonymous »

Я работаю над приложением Kivy, в котором мне нужно динамически регулировать положение и высоту определенных виджетов. Однако, что бы я ни пытался, свойства pos и pos_hint, похоже, не влияют на размещение виджетов в моем макете. В частности, я использую BoxLayout для вертикальной организации виджетов, но изменение pos или pos_hint макета и отдельных виджетов не оказывает видимого влияния на их расположение.
Вот что я пробовал:
Использование pos_hint в виджетах TextInput и Button для изменения их вертикального расположения.
Настройка свойства pos в BoxLayout для перемещения всего макета.
/>Установка высоты виджетов и использование size_hint_y для управления размером виджетов.
Попытка переместить макет вверх, чтобы освободить место в нижней части экрана.
Ни один из этих подходов, похоже, не дает никакого эффекта . Макет остается в исходном положении, а виджеты не размещаются и не изменяются должным образом.
Мой код:

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

from kivy.app import App
from kivy.uix.textinput import TextInput
from kivy.uix.scrollview import ScrollView
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.core.window import Window
from kivy.uix.label import Label
from kivy.clock import Clock
import random

class LongStringApp(App):
def build(self):
# Set the window size (optional)
Window.size = (800, 600)

# Create a long string of text
long_string = ("""Therefore, I urge you, brothers and sisters, in view of God’s mercy, to offer your bodies as a living sacrifice, holy and pleasing to God—this is your true and proper worship.""")
self.original_text = long_string

# Split the text into words
words = long_string.split()

num_blanks = len(words) // 6

# Randomly select which words to replace with blanks
indices_to_blank = random.sample(range(len(words)), num_blanks)

# Replace the selected words with underscores of the same length
for i in indices_to_blank:
word_length = len(words[i])
words[i] = "_" * word_length  # Replace with underscores

# Reconstruct the string with blanks
modified_string = "  ".join(words)

# Variables for easy adjustment
self.HEIGHT_PERCENTAGE_TEXT = 0.8  # 80% of the screen height for the TextInput
self.HEIGHT_PERCENTAGE_BUTTON = 0.1  # 10% of the screen height for the Button
self.POS_PERCENTAGE_LAYOUT = 0.6  # Position of the entire layout, starting from the top

# Create a BoxLayout to hold the TextInput and Submit Button
self.layout = BoxLayout(orientation='vertical', padding=10, spacing=10)

# Create a TextInput widget to allow the user to edit the string
self.text_input = TextInput(text=modified_string, font_size=20, multiline=True, size_hint_y=None,
background_color=(0, 0, 0, 1), foreground_color=(1, 1, 1, 1))  # Black background, white text
self.text_input.height = Window.height * self.HEIGHT_PERCENTAGE_TEXT  # Set the height of the TextInput
self.text_input.text_size = (Window.width - 20, None)  # Set the text size for wrapping
self.text_input.bind(width=self.update_text_size)  # Bind width to text_size for wrapping

# Add the TextInput to the layout
self.layout.add_widget(self.text_input)

# Create a submit button to check if the filled-in text matches the original
submit_button = Button(text="Submit", size_hint_y=None, height=50, background_color=(0.2, 0.6, 0.2, 1))

# Set height for the Button manually
submit_button.height = Window.height * self.HEIGHT_PERCENTAGE_BUTTON  # Set the height of the Button

submit_button.bind(on_press=self.check_answers)

# Add the button to the layout
self.layout.add_widget(submit_button)

# Create a ScrollView and add the layout to it
scroll_view = ScrollView()
scroll_view.add_widget(self.layout)

# Schedule the scroll to the top after the window has been fully created
Clock.schedule_once(self.scroll_to_top, 0.1)

# Move the entire layout up by 20% of the screen height (adjusting the top margin)
self.layout.pos_hint = {'top': self.POS_PERCENTAGE_LAYOUT}  # Set the top position to be 80% from the top

return scroll_view

def update_text_size(self, *args):
# Update the text_size with the current width of the TextInput minus padding
self.text_input.text_size = (self.layout.width - 20, None)

def scroll_to_top(self, dt):
# This function will set the ScrollView to the top
self.root.scroll_y = 1

# Set focus to the TextInput and move the cursor to the start
self.text_input.focus = True
self.text_input.cursor = (0, 0)  # Moves the cursor to the start

def check_answers(self, instance):
# Get the filled-in text from the TextInput
filled_text = self.text_input.text.strip()

# Remove any extra spaces for comparison
original_text = self.original_text
original_text_clean = ' '.join(original_text.split())
filled_text_clean = ' '.join(filled_text.split())

# Check if the filled text matches the original text
if filled_text_clean == original_text_clean:
result_text = "Correct! You filled in all the blanks correctly."
else:
result_text = "There are some mistakes. Please try again."

# Create a result label to show feedback
result_label = Label(text=result_text, size_hint=(1, None), height=50, font_size=18, color=(1, 1, 1, 1))

# Add the result label to the layout (within BoxLayout)
self.layout.add_widget(result_label)

# Optionally remove the result label after a few seconds
Clock.schedule_once(lambda dt: self.remove_result_label(result_label), 2)

def remove_result_label(self, label):
self.layout.remove_widget(label)

if __name__ == '__main__':
LongStringApp().run()
Чего я ожидаю:
Свойства pos_hint и pos должны регулировать размещение виджетов TextInput и Button, а также всего макета.
Я хочу создать пространство в верхней части страницы. нижняя часть (20% окна должна быть пустой, нижняя 20%) экрана путем смещения макета и виджетов вверх на 20%.
Что происходит:
Виджеты остаются на исходных позициях, и корректировка положения или pos_hint не влияет на макет.
Дополнительная информация:
Я также пробовал использовать size_hint_y для регулировки высоты, но это изменяет только размер виджетов, а не их положение.
Может ли кто-нибудь помочь мне понять, почему свойства pos и pos_hint не работают для размещения виджетов в моем приложении Kivy?

Подробнее здесь: https://stackoverflow.com/questions/792 ... t-placemen
Ответить

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

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

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

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

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